Search code examples
ccommand-line-argumentsfopenargvargc

Passing in filename from command line to read file content


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.


Solution

  • 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 */  
    }