Search code examples
cfilecommand-linestdinfgetc

C: Printing words from a file using fgetc


I'm trying to write a simple main function that takes in a file through the command line, and prints all the words in the file.

However, I've followed several tutorials that just don't seem to work. Here's my code:

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

    if (argc < 2) return 1;
    char * filename = argv[1];
    FILE* file = fopen(filename, "r");

    if(file == NULL) {
      perror("Error opening file");
      return(1);
   }

   char c;
   while((c = fgetc(file)) != EOF)
    {
        if(c == ' ' || c == '\n')
        {
            printf("\n");
        }
        else
        {
            printf("%c", c);
        }
    }
    printf("Done.");
    fclose(file);
    return 0;
}

So far it has returned nothing, and doesn't show an error. The command line looks like this:

C:\Users\<USERNAME>\Desktop\C_C++>program.exe < file.txt

C:\Users\<USERNAME>\Desktop\C_C++>program.exe > file.txt

C:\Users\<USERNAME>\Desktop\C_C++>

It's using a windows command line. I didn't know whether or not I had to use > or < when passing in a file parameter, but I've also just used the file's name in place of filename in FILE* file = fopen(filename, "r"); to just open it directly instead of passing the filename as a parameter, but nothing shows.

I have no idea what is going wrong.


Solution

  • fgetc() returns int, not char. You need to declare

    int c;
    

    Otherwise, there's a possibility that the test for EOF will never succeed.

    Your program expects the filename as a command-line argument, it doesn't read from standard input. So you have to give the filename as an argument, not use input redirection. The program is exiting immediately because argc is 1.

    program.exe file.txt
    

    You should add an error message so you'll know this is the problem:

    if (argc < 2) {
        printf("Usage: %s filename\n", argv[0]);
        return 1;
    }