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
  • 682
  • 2
  • 17
  • 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
  • 445,704
  • 82
  • 492
  • 529
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,409
  • 1
  • 25
  • 36