Linux下C语言文件拷贝程序编译及运行报错问题求助
问题解决指南
一、编译错误:cannot use executable file 'main.' as input to a link
- 原因:当前目录存在名为
main.的无效可执行文件,gcc在链接阶段误将其当作输入文件处理 - 解决步骤:
- 删除错误文件:
rm -f main. - 重新编译(无需
-lm,代码未用到数学库):gcc -o main main.c
- 删除错误文件:
二、运行错误:Source file can't be opened: : No such file or directory
- 直接诱因:运行了中间目标文件
main.o而非最终可执行文件,且代码存在逻辑错误导致源文件名未被正确获取 - 分步修复:
- 运行正确文件:编译完成后执行
./main,main.o是编译生成的中间文件,无法直接运行 - 修复代码逻辑问题:
- 循环条件失效:原
PromptUser函数中,while (strcmp(inStr, ""))初始时inStr为空字符串,strcmp返回0,循环直接跳过,导致源文件名始终为空。需将循环改为无限循环直到获取有效文件:
原代码:
修改为:while (strcmp (inStr, ""))while (1) - 文件资源泄漏:
FileExists函数打开文件后未关闭,添加fclose(filePtr);避免资源浪费 - 换行符语法错误:将代码中
printf(" Success! ");这类错误写法替换为printf("\nSuccess!\n"); - 拼写错误:将
different namme修正为different name
- 循环条件失效:原
- 运行正确文件:编译完成后执行
修复后的完整代码
#include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include <string.h> // 检查文件是否存在 bool FileExists(char *fileName) { FILE *filePtr = fopen(fileName, "r"); if (!filePtr) { return false; } fclose(filePtr); // 关闭打开的文件 return true; } // 拷贝源文件到目标文件 void Copy(char *out, char *in) { int c; FILE *inPtr = fopen(in, "r"); FILE *outPtr = fopen(out, "w"); if (!inPtr) { perror("Source file can't be opened: "); exit(1); } if (!outPtr) { perror("Destination file can't be opened: "); exit(1); } while ((c = fgetc(inPtr)) != EOF) { fputc(c, outPtr); } printf("\nSuccess!\n"); fclose(inPtr); fclose(outPtr); } // 提示用户输入文件名 void PromptUser() { char str[32], inStr[32], outStr[32]; char *strPtr = str; // 获取源文件名并检查存在性 while (1) { printf("Enter name of source file: "); scanf("%s", strPtr); if (FileExists(strPtr)) { strcpy(inStr, str); break; } else { printf("File does not exist. File can't be opened!\n"); } } // 获取目标文件名并检查是否已存在 while (1) { printf("Enter name of destination file: "); scanf("%s", strPtr); if (!FileExists(strPtr)) { strcpy(outStr, str); break; } else { printf("File already exists! Please enter a different name.\n"); } } Copy(outStr, inStr); } int main() { PromptUser(); return EXIT_SUCCESS; }
编译运行流程
- 清理旧文件:
rm -f main main. main.o - 编译:
gcc -o main main.c - 运行:
./main - 按提示输入源文件名和目标文件名即可完成拷贝
内容的提问来源于stack exchange,提问作者Hiếu Võ Trần Minh
相关产品推荐
相关产品推荐

