简体   繁体   中英

Getting error while using fgets in ansi c to open file

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 :)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM