文件问题
#include <stdio.h>#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fp1,*fp2;
char str;
if((fp1=fopen("D:\\test1.txt","r"))==NULL)
{
printf("can not open file\n");
exit (0);
}
if((fp2=fopen("D:\\test2.txt","w+"))==NULL)
{
printf("can not open file\n");
exit (0);
};
while ((strlen(fgets(str,128,fp1)))>0)
{
fputs(str,fp2);
printf("%s",str);
}
fclose(fp1);
fclose(fp2);
}
这样的一段代码,写入D盘中,text1是有内容的,运行后只创建text2,却写不进去,显示屏也是有内容的,是我电脑问题吗?你们试试哈 循环改成这样while ((fgets(str, 128, fp1)!=NULL))试试
fgets函数读不到会返回NULL,你strlen(NULL)>0啥意思啊,改过来吧 入门者 发表于 2020-3-25 23:13
循环改成这样while ((fgets(str, 128, fp1)!=NULL))试试
fgets函数读不到会返回NULL,你strlen(NULL)>0啥 ...
出错,编译都过不了 #include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 65535
int main()
{
FILE *fp1, *fp2;
char str;
if((fp1 = fopen("1.txt", "r")) == NULL)
{
printf("Opening file error!\n");
exit(EXIT_FAILURE);
}
if((fp2 = fopen("2.txt", "w")) == NULL)
{
printf("Opening file error!\n");
exit(EXIT_FAILURE);
}
while(!feof(fp1))
{
if(fgets(str, MAXSIZE, fp1) != NULL)
{
fputs(str, fp2);
printf("%s", str);
}
}
fclose(fp1);
fclose(fp2);
return 0;
}
我的可以运行,文件也创建成功了。你的程序的问题在于strlen()函数里的参数不可以传入空指针,编译正确但是运行会产生错误。
这个是直接用你的改的,并没有报错,文件创建成功,且将1.txt成功复制到3.txt了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
FILE *fp1,*fp2;
char str;
if((fp1=fopen("1.txt","r"))==NULL)
{
printf("can not open file\n");
exit(0);
}
if((fp2=fopen("3.txt","w+"))==NULL)
{
printf("can not open file\n");
exit(0);
};
while (fgets(str,128,fp1) != NULL)
{
fputs(str,fp2);
printf("%s",str);
}
fclose(fp1);
fclose(fp2);
}
张世来4610484 发表于 2020-3-26 11:11
出错,编译都过不了
我在vs2013三上运行确实没问题
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1, *fp2;
char str;
if ((fp1 = fopen("test1.txt", "r")) == NULL)
{
printf("can not open file\n");
exit(0);
}
if ((fp2 = fopen("test2.txt", "w+")) == NULL)
{
printf("can not open file\n");
exit(0);
};
while ((fgets(str, 128, fp1)!=NULL))
{
fputs(str, fp2);
printf("%s", str);
}
fclose(fp1);
fclose(fp2);
return 0;
}
页:
[1]