文本文件数据读取与显示,代码运行错误

#include<stdio.h>
#include<stdlib.h>
int main()
{  FILE *fp;
   int i=0;
   char str[10][81];  //每行最多80个字符
   if((fp=fopen("data3.txt","w"))==NULL)//打开文件data3.txt
   {  printf("%s open error!\n","data3.txt");
      exit(1);
   }
   while(!feof(fp))
   {  
fgets(str[i],81,fp);//读取文件中的一行内容
  printf("%s",str[i]);
      i++;
   }
   fclose(fp);
   return 0;
}

你代码中,fopen函数调用的是 "w" 标识,表示打开文件并写入。如果文件不存在,会新建文件。如果文件已存在,原有内容会被清空。而在这个程序中,我们要的是读取文件中的内容,所以应该使用 "r" 标识,而不是 "w"。

修改后的代码如下

#include<stdio.h>
#include<stdlib.h>
int main() {
    FILE *fp;
    int i=0;
    char str[10][81];
    //每行最多80个字符
    if((fp=fopen("data3.txt","r"))==NULL)//打开文件data3.txt {
        printf("%s open error!\n","data3.txt");
        exit(1);
    }
    while(!feof(fp)) {
        fgets(str[i],81,fp);
        //读取文件中的一行内容
        printf("%s",str[i]);
        i++;
    }
    fclose(fp);
    return 0;
}

"w"改成"r",注意文件路径有没有错!