You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下C语言文件拷贝程序编译及运行报错问题求助

问题解决指南
  • 原因:当前目录存在名为main.的无效可执行文件,gcc在链接阶段误将其当作输入文件处理
  • 解决步骤:
    1. 删除错误文件:rm -f main.
    2. 重新编译(无需-lm,代码未用到数学库):gcc -o main main.c

二、运行错误:Source file can't be opened: : No such file or directory

  • 直接诱因:运行了中间目标文件main.o而非最终可执行文件,且代码存在逻辑错误导致源文件名未被正确获取
  • 分步修复:
    1. 运行正确文件:编译完成后执行./main,main.o是编译生成的中间文件,无法直接运行
    2. 修复代码逻辑问题:
      • 循环条件失效:原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;
}

编译运行流程

  1. 清理旧文件:rm -f main main. main.o
  2. 编译:gcc -o main main.c
  3. 运行:./main
  4. 按提示输入源文件名和目标文件名即可完成拷贝

内容的提问来源于stack exchange,提问作者Hiếu Võ Trần Minh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 23:50:34