首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

本人初学c,这个小程序读写资料结束点出了点毛病,求大神指点一二

2013-08-16 
本人初学c,这个小程序读写文件结束点出了点毛病,求大神指点一二#includestdio.h#includestring.h#incl

本人初学c,这个小程序读写文件结束点出了点毛病,求大神指点一二
#include<stdio.h>
#include<string.h>
#include<windows.h>
FILE*p;
struct xiaozi
{
      int aa;
      int bb;
      char cc;
      float dd;
      char ee[20];
      int ff[10];
}mmm,nnn;
#define len sizeof(xiaozi)
int main()
{
    struct xiaozi * pp=&mmm,*ppp=&nnn;
     int a,b,f[10];char c,e[20];
     gets(e);
     strcpy(mmm.ee,e);
     if((p=fopen("D:\\123.txt","a"))==NULL)
     p=fopen("D:\\123.txt","w");
     fwrite(pp,len,1,p);
     fclose(p);
     p=fopen("D:\\123.txt","r");
     while(!feof(p))//最后一个数据总是输出两遍,用while(p!=NULL)则到最后一个数据时停不下来了
     {
         fread(ppp,len,1,p);
                 printf("%d\t%d\t%c\t%f\t%s\t%d\t\n",nnn.aa,nnn.bb,nnn.cc,nnn.dd,nnn.ee,nnn.ff[1]);
         Sleep(5000);
     }
  return 0;
} C
[解决办法]

不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
 if (条件1) break;
 //...
 if (条件2) continue;
 //...
 if (条件3) return;
 //...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
 a=fgetc(f);
 //...
 b=fgetc(f);//可能此时已经feof了!
 //...
}
而这样写就没有问题:
whlie (1) {
 a=fgetc(f);
 if (feof(f)) break;
 //...
 b=fgetc(f);
 if (feof(f)) break;


 //...
}
类似的例子还可以举很多。


[解决办法]
点错了,还没说话,
你代码太乱了,我没整理了,看不下去拉!

推荐你先去看看 高质量c编程吧!

引用:

#include <stdlib.h>

#include<stdio.h>
#include<string.h>
//#include<windows.h>


#define len sizeof(xiaozi)

struct xiaozi
{
    int aa; 
    int bb; 
    char cc; 
    float dd; 
    char ee[20];
    int ff[10];
}mmm,nnn;

int main()
{
    FILE*p;
    struct xiaozi * pp=&mmm,*ppp=&nnn;
    int a,b,f[10];char c,e[20];
    gets(e);
        
    strcpy(mmm.ee,e);
    if((p=fopen("D:\\123.txt","a"))==NULL)
        p=fopen("D:\\123.txt","w");
    fwrite(pp,len,1,p);
    fclose(p);
    p=fopen("D:\\123.txt","r");
    while(!feof(p))//最后一个数据总是输出两遍,用while(p!=NULL)则到最后一个数据时停不下来了
    {   
        fread(ppp,len,1,p);
        printf("%d\t%d\t%c\t%f\t%s\t%d\t\n",nnn.aa,nnn.bb,nnn.cc,nnn.dd,nnn.ee,nnn.ff[1]);
        Sleep(5000);
    }   
    return 0;



[解决办法]
#define len sizeof(xiaozi)
改为
#define len sizeof(struct xiaozi)
[解决办法]
     if((p=fopen("D:\\123.txt","a"))==NULL)
     p=fopen("D:\\123.txt","w");
这样写感觉很奇怪

一般都是
  if((p=fopen("D:\\123.txt","a"))==NULL)
      return -1;
[解决办法]
这里只有一个main函数
FILE*p;没必要声明为全局变量  
你以后就知道  一个大型工程中全局变量越少越好 
[解决办法]
feof() 这个函数是当读到文件结束符就返回 true 值,而非到文件最后一个字符,所以当读完文件最后一个字符时,还会读一次


http://blog.sina.com.cn/s/blog_705a5ff00101ab5d.html
[解决办法]
推荐使用WinHex软件查看硬盘或文件或内存中的原始字节内容。

不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待

fopen("...","...b");fread,fwrite,fclose  //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了

热点排行