felicia white felicia white - 25 days ago 10
C Question

Making a command line application from a C program

How do I convert this program(binary.c) into a command line application so it can read any binary text (e.g.

binary1.txt
) file and then convert it to ASCII? For example I want to do:

./binary < binary1.txt


and it should print


Hello World!


at the command line.

This is my program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *f_ptr;
f_ptr = fopen("binary1.txt", "r");
if (f_ptr == NULL){
printf("Error opening binary1.txt");
return 1;
}

while(1){
int ch = fgetc(f_ptr);
if(ch == EOF)
break;

printf("%c",ch);

}

fclose(f_ptr);
return 0;
}

Answer Source

From what I understand you are trying to pass the filename to your program and not sure how to do that. In that case you might want to do this

int main(int argc, char* argv[])
{
  if(argc>1)
  std::string filename = argv[1];
  //now you have the file in the filename

 // your code 
 return 0;
}

so when you execute just do this

./binary binary1.txt

you don't need to use < and I am assuming that both your executable and text file are in the same directory