程序存在对应文件却提示No such file or directory的问题求助
问题解决:fgets读取文件名导致fopen失败
核心问题是fgets会将用户输入时按下的换行符\n一并读入字符串,比如输入test.txt回车后,DataFile实际存储的是"test.txt\n",而系统中不存在这个带换行的文件名,因此fopen返回找不到文件的错误。
另外代码还有一个潜在问题:当通过命令行参数传入文件名时,DataFile指向的是argv[1](系统分配的内存),此时调用free(DataFile)会触发未定义行为,必须只释放自己malloc分配的内存。
修正后的代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define FILE_SIZE 256 // 假设FILE_SIZE是已定义的宏 int main(int argc, char *argv[]) { char* DataFile = NULL; int is_malloced = 0; // 标记是否是malloc分配的内存 if (argc < 2) { printf("Enter the name of the file (relative or absolute): "); size_t bufsize = FILE_SIZE; DataFile = (char*)malloc(bufsize); if (DataFile == NULL) { perror("Memory allocation failed"); return EXIT_FAILURE; } is_malloced = 1; if (fgets(DataFile, bufsize, stdin) == NULL) { perror("Error reading input"); free(DataFile); return EXIT_FAILURE; } // 去掉末尾的换行符 size_t len = strlen(DataFile); if (len > 0 && DataFile[len-1] == '\n') { DataFile[len-1] = '\0'; } } else { DataFile = argv[1]; } FILE* fd = fopen(DataFile, "r"); if (fd == NULL) { perror("Cannot open the file"); if (is_malloced) { // 只释放自己分配的内存 free(DataFile); } exit(EXIT_FAILURE); } else { printf("Opened the file\n"); // 记得后续关闭文件 fclose(fd); } if (is_malloced) { free(DataFile); } return EXIT_SUCCESS; }
关键修正点:
- 添加
is_malloced标记,确保只释放自己通过malloc分配的内存,避免对argv内存的非法释放。 - 使用
strlen获取输入字符串长度,检查末尾是否为\n,如果是则替换为字符串结束符\0,去除多余的换行符。
测试时,输入文件名后回车,程序会自动去掉换行符,此时fopen就能正确找到对应文件了。
内容的提问来源于stack exchange,提问作者Mihajlo Spasic
相关产品推荐
相关产品推荐

