2

I'm trying to create/open a file using c. I enter the name using the fgets command, so I can not overflow the buffer, like this:

void main() {
    printf("Enter file name: ");
    char * fileName = (char *) calloc(MAX_BUFFER_SIZE, sizeof(char));
    fgets(fileName, MAX_BUFFER_SIZE, stdin);
    FILE *inputFile = fopen(fileName, "w");
    if(inputFile==NULL) perror(fileName);
}

Using the debugger, I can see that the value I entered for the name of the file, is the one I wish, but the fopen function returns NULL pointer and I get the "Invalid argument" error. If I use scanf("%s", fileName) instead there is no problem and the file is created but in this way I could overflow the buffer. Any ideas why the first example is not working? Thanks in advance :)

mjekov
  • 652
  • 1
  • 16
  • 32

2 Answers2

4

The string read by fgets might have a newline at the end. You'll have to remove it before you use the string in fopen.

How to remove the newline at the end?

Community
  • 1
  • 1
codaddict
  • 429,241
  • 80
  • 483
  • 523
  • @azlisum Then accept the answer according to [here](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – Eitan T May 14 '12 at 07:31
2

fgets() treats newlines differently than scanf("%s") or gets(). Unlike them, fgets() includes the newline in the string. After typing the filename, you pressed enter which probably included the newline into your filename, hence rendering it invalid.

Imp
  • 8,079
  • 1
  • 24
  • 36