程序在从文件读取时崩溃。 C

问题描述:

下面的代码是将文本文件复制到另一个文件中。 其失败。 assertion error(stream!= NULL)程序在从文件读取时崩溃。 C

fp = fopen("quiz.txt", "w"); 
fp2 = fopen("output.txt", "r"); 

number_of_conversions = fscanf(fp2, "%c", &c); 

while (number_of_conversions != 0 && number_of_conversions != EOF){ 
    fputc(c,fp); 
    number_of_conversions = fscanf(fp2, "%c", &c); 
} 
fclose(fp2); 
fclose(fp); 
+0

代码部分被拧紧。 '\t fp = fopen(“quiz.txt”,“w”); \t fp2 = fopen(“output.txt”,“r”); \t number_of_conversions =的fscanf(FP2, “%C”,&c); \t而(number_of_conversions = 0 && number_of_conversions = EOF){ \t \t的fputc(C,FP);! \t \t \t number_of_conversions =的fscanf (FP2, “%C”,&c); \t} \t FCLOSE(FP2); \t FCLOSE(FP);' –

+0

我看到在没有'assert'码。看起来很奇怪,你正在从一个名为'output.txt'的文件中读取数据。 – user3386109

+0

我已经写数据到它现在正在写数据回输入文件。 –

在使用返回的文件指针前总是检查fopen()的成功。

如果fopen()失败,它将返回NULL,并使用它进一步将导致undefined behaviour。因此,在fopen()调用后立即进行NULL检查。另外,FWIW,如果fopen()失败,则不会打开FILE *,您也不需要拨打fclose()