gpt4 book ai didi

c - 如果文件为空,我的代码将返回段错误,如果文件不为空,则返回段错误?

转载 作者:行者123 更新时间:2023-11-30 17:29:48 25 4
gpt4 key购买 nike

我正在尝试将源文件复制到目标文件,如果目标文件存在,则与用户交互或要求用户覆盖,如果它为空,则将其复制到目标文件

如果文件为空,我的代码将返回段错误,如果文件不为空,则返回正常?请帮我解决?

 #include<stdio.h>
int main(int argc,char**argv)
{
char ch,us;
FILE *fp,*fp1;
fp1=fopen(argv[2],"r+");// i want to use r+ mode only
if(fp1!=NULL)
{
printf("do u want to overwrite\n");
scanf("%c",&us);
if(us=='y');
else
return;
}
fp=fopen(argv[1],"r"); // its good when file is not NULL but
//its segmentation fault when fp1 is empty?
while((ch=fgetc(fp))!=EOF)
fputc(ch,fp1);
}

最佳答案

在您的情况下,fp1 在您尝试在 while 循环中写入的地方为 NULL。此外,您应该截断目标文件以清理旧数据,因此使用 "w" 重新打开。

您应该将代码更新为

fp1=fopen(argv[2],"r+");// i want to use r+ mode only
if(fp1!=NULL)
{
fclose(fp); //close the file
printf("do u want to overwrite\n");
scanf("%c",&us);
if(us=='y');
else
return;
}
fp1=fopen(argv[2],"w"); //open with write.
fp=fopen(argv[1],"r");

关于c - 如果文件为空,我的代码将返回段错误,如果文件不为空,则返回段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25498926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com