简体   繁体   English

在ANSI C中使用fgets打开文件时出错

[英]Getting error while using fgets in ansi c to open file

I'm trying to create/open a file using c. 我正在尝试使用c创建/打开文件。 I enter the name using the fgets command, so I can not overflow the buffer, like this: 我使用fgets命令输入名称,所以不会像这样溢出缓冲区:

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. 使用调试器,我可以看到我为文件名输入的值是我想要的值,但是fopen函数返回NULL指针,并且出现“无效参数”错误。 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. 如果我使用scanf("%s", fileName)相反,就没有问题,并且文件已创建,但是通过这种方式,我可能会使缓冲区溢出。 Any ideas why the first example is not working? 任何想法为什么第一个示例不起作用? Thanks in advance :) 提前致谢 :)

The string read by fgets might have a newline at the end. fgets读取的字符串的结尾可能会有换行符。 You'll have to remove it before you use the string in fopen . fopen使用字符串之前,必须将其删除。

How to remove the newline at the end? 如何最后删除换行符?

fgets() treats newlines differently than scanf("%s") or gets() . fgets()对换行符的处理不同于scanf("%s")gets() Unlike them, fgets() includes the newline in the string. 与它们不同, fgets()在字符串中包含换行符。 After typing the filename, you pressed enter which probably included the newline into your filename, hence rendering it invalid. 输入文件名后,按Enter键,其中可能将换行符包含在文件名中,因此使其无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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