Aaron James Rasmussen
Aaron James Rasmussen

Reputation: 17

How to use fopen to open a file that has a name specified by the user?

Right now I have this:

printf("Please enter your file name with\nthe file type then hit enter followed by ctrl+z\nthen enter 1 final time\n");
char tempChar;
int counter = 0;
char fileName[1000];
int boolean1 = 0;
    while(boolean1 == 0)
    {
        tempChar = getchar();
        if(tempChar == EOF)
            break;
        else
            fileName[counter] = tempChar;
        counter++;
}

where fileName would be the name of the file. This command works which is awesome and gives me a char array with the name they want. However, I don't know how to pass this to fopen(). I've tried fopen(fileName, "r"); and I've tried it with quotes over filename. I also tried doing fopen("%c",&fileName,"r"); I believe this is happening because of the extra garbage that comes after in the 1000 length character array but how do I resolve the issue?

Upvotes: 1

Views: 400

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

I think, you don't need to get and EOF, explicitly, just check for the newline ('\n'), then null terminate the array and pass that to fopen().

Something like

while(1)
    {
        tempChar = getchar();
        if(tempChar == '\n'){
            fileName[counter] = '\0';  //null-terminate
            break;
            }
        else
            fileName[counter] = tempChar;
        counter++;
}

will do the job.

That said, FWIW,

  • getchar() returns an int, which may not fit in a char (example in hand, EOF), so change the tempChar to int type, for better.
  • always initialize your local variables, like char fileName[1000] = {0};

Another easier approach would be using fgets() to read the input from the user at once, process (remove terminating null) and pass that to fopen().

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49920

Strings in C need to be terminated with a null character ('\0'), which you failed to do.

Upvotes: 1

Related Questions