-2

I have a function ./transform that needs to take in two command line arguments for an input and output file.

Like so: ./transform "inputfile" "outputfile"

I am then trying to read the file using fopen to store each character in the file into a character array char token[1024]. The total number of characters in the input file will always be <= 1024.

I am receiving errors about fopen not having the right amount of arguments. Here is pseudo-code of what I am trying to accomplish.

void main(FILE *inputFile, FILE *outputFile){
    char token[1024];
    token = fopen(&inputFile, "r");
}

Yes, I am aware I am trying to assign a FILE value to a Char value... I wrote it this way to show that I want each character from the inputFile stored in the character array. I am unsure how to do so properly. After executing the program's code (converting hex and int values from file to ASCII), I need to save the converted ASCII text into the user-defined output file.

jasonsogan
  • 11
  • 1
  • 4
  • 2
    The main function has 2 arguments, int argc - the number of arguments, and char* argv[] - a string array of the arguments passed in. It can't take a FILE as a cmdline argument. – Matt Sep 16 '18 at 01:00
  • 1
    Also, fopen takes in a string as the first argument, not a file. – Matt Sep 16 '18 at 01:01
  • @Matt, I cannot use strings, would passing in character arrays like so work? main(char inputFile[], char outputFile][]){} – jasonsogan Sep 16 '18 at 01:02
  • As you mentioned, fopen returns a file pointer, not a string, and c wont let you cast that automatically. You need to assign the output to a var of type FILE, then read that into your string. – Matt Sep 16 '18 at 01:04
  • When I say string, I'm referring to a null terminated char array. If you want to use commandline args, you need to use the argc/argv arguments. – Matt Sep 16 '18 at 01:06

1 Answers1

0

There are few issues with the code you tried, firstly here

void main(FILE *inputFile, FILE *outputFile){ }

you are trying to change prototype of main() which is not correct. According to C Standard Section 5.1.2.2.1 Program startup, either it should be

int main(void) { /* ... */ }

or

int main(int argc, char *argv[]) { /* ... */ }

So make it like

int main(int argc, char *argv[]) {
    /*some_code */
}

Next, to open a file using fopen() from command line, this

token = fopen(&inputFile, "r");

is completely wrong as fopen() returns argument of FILE* not char* & argument you provided to fopen() also wrong. Read then manual page of fopen() ,it says

FILE *fopen(const char *path, const char *mode);

Sample code

int main(int argc, char *argv[]) {
  if( argc!= 3 ) { /*if user input is not correct, inform user */
     printf("./transform inputfile outputfile \n");
     return 0;
  }
  FILE *fp = fopen(argv[1],"r); 
  if(fp == NULL) {
     /* error handling */
     return 0;
  }
  /* do_stuff_with_fp */  
}
Achal
  • 11,821
  • 2
  • 15
  • 37