Eric Unkown
Eric Unkown

Reputation: 1

Passing a file as an argument and reading the data

So I am trying to write a C code that takes in a file name as the argument and reads the file and stores it into an array. I have tried but failed epically :(

Can anyone please point me in the right direction? Here is what I came up with (I know it may be completely off track :/ )

#include <stdio.h>

int main (int argc, char *argv[]) {
   char content[500];
   int k=0;
   FILE* inputF;
   inputF = fopen("argv[0]", "r");

   do {
       fscanf(inputF, "%c", &content[k]);
       k++;
   } while (content[k] != EOF ); 

return 0;
}

Upvotes: 0

Views: 6953

Answers (2)

teppic
teppic

Reputation: 8205

A couple of points to help get you started:

argc is the number of arguments, and the first argv pointer is the name of the executable file. The second is what you want.

You have to check that your file pointer is valid before trying to use it.

Maybe look at using fgetc to read each character, and test for EOF.

You need to check that you don't overrun your content buffer.

If you're stuck, here's an example of a main loop using a do while:

do {
    ch = fgetc(fp);
    content[a] = ch;
    a++;
} while (ch != EOF && a < 500);

This will store an EOF (if found) in your array.

Upvotes: 1

user1944441
user1944441

Reputation:

You passed "argv[0]" string to fopen, I'm sure that isn't the name of you file you are trying to open.

You should pass a pointer to a string that contains the file name.

inputF = fopen(argv[1], "r");


Also note the usage of argv[1] not argv[0].

argv[0] contains the full filepath and name of the executable and argv[1] the first string entered as command line parameter.

Upvotes: 3

Related Questions