回 帖 发 新 帖 刷新版面

主题:C语言读取数据文件问题

  int data[2793][4];                                                         
  int i,j,k,;                                                                  
   /*打开文件 读取数据*/                                                        
  FILE *fp=fopen("C:\\Users\\acer\\Desktop\\201212281800_no8B_19_17.txt","r"); 
  if(!fp)                                                                      
  {                                                                            
   printf("can't open file\n");                                                
   return -1;                                                                  
  }                                                                            
  while(!feof(fp))                                                             
  {                                                                            
    for(i=0;i<2793;i++)                                                        
    {                                                                          
     for(j=0;j<4;j++)                                                          
     {                                                                         
      fscanf(fp,"%d",&data[i][j]);                                             
   printf("%6d",data[i][j]);                                                   
     }
  printf("\n");                                                                                                                                      
    }                                                                          
   }                                                                                                                                            
 fclose(fp);    

请问读取的数据问什么和原数据文件上的数据不一样 ?                                                  

回复列表 (共1个回复)

沙发

我想lz可能要问,当文件的内容为如下:
1 3 4 5
2 4 6 8
3 6 9 12
4 8 5 4

为什么内容输出了两遍是吧?
lz判断文件结束的写法是while( !feof(fp) );
feof()作用就是判断文件结尾(但是发生读取错误也会返回EOF的,建议lz查下),但是在txt文件中看到的结尾并不真正是文件结尾,
注意上面的文件内容后面多输入了n(n>=1)个回车。
个人觉得lz这么写代码有些问题。既然lz不关注那些重点,也不便多说。
最后补充一句,用while( !feof(fp) );的时候斟酌下。

我来回复

您尚未登录,请登录后再回复。点此登录或注册