入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

c语言读取该文件内的数据

创建时间:2007-11-03 投稿人: 浏览次数:9169

采集了一系列数据(数据信号,由0和1表示),保存在data.txt文件中。想用c语言读取该文件内的数据,数一下在一起的0的个数和1的个数。如:若data.txt内的内容为11010110(每个数据独占一行,当然数据比这多很多,反正一共38kb)得到的结果应该是2 1 1 1 2 1(每个数据独占一行),然后保存在新的文件中,如result.txt。
  网站上有篇文章编写了如下代码:
#include <stdio.h>
#include <stdlib.h>
void main()
{
    int curNum;
    FILE *fp;
    FILE *pNewFile;
    char curChar;
    char preChar;
   //int itemsNum=0; //得到数据条数
    pNewFile=fopen("result.txt","w");
    if(NULL==pNewFile)
    {
        printf("Can"t open or create the file named result.txt.");
        exit(0);
    }

    if((fp=fopen("data0.txt","r"))==NULL)
    {
        printf("can not open the file named date.txt./n");
        exit(0);
    }
    if(!feof(fp))
    {
        do
        {
            fread(&preChar,1,1,fp);
        }while(!feof(fp) && preChar!="1" && preChar!="0");
        curNum=1;
    }
    else
    {
        printf("there is no valible data in the file.");
        exit(0);
    }

    while(!feof(fp))
    {
        char temp;
        do
        {
            fread(&temp,1,1,fp);
        }while(!feof(fp) && temp!="1" && temp!="0");

        if(feof(fp)) //文件结束,没有读取到有效数据,不再执行内部代码
            break;
        else
            curChar=temp;

        if(preChar==curChar)
            curNum++;
        else
        {
            fprintf(pNewFile,"%d/n",curNum);
            printf("%c: %d/n",preChar,curNum);
            curNum=1;
           // itemsNum++;
        }
        preChar=curChar;
    }
    fprintf(pNewFile,"%d",curNum);
    printf("%c: %d/n",curChar,curNum);
    //printf("/n/t%d/n/n",itemsNum+1);
    fclose(fp);
    fclose(pNewFile);
}
/////
本人的改进版
#include <stdio.h>
#include <stdlib.h>
void main()
{
    int curnum=1;
    FILE *fp;
    FILE *pNewFile;
 
   //int itemsNum=0; //得到数据条数
    pNewFile=fopen("result.txt","w");
    if(NULL==pNewFile)
    {
        printf("Can"t open or create the file named result.txt.");
        exit(0);
    }

    if((fp=fopen("data.txt","r"))==NULL)
    {
        printf("can not open the file named date.txt./n");
        exit(0);
    }
     char temp;
  char pretemp;
   fread(&temp,1,1,fp);
  
    pretemp=temp;
        do
        {
  
            fread(&temp,1,1,fp);
   if (temp!="1" && temp!="0") continue ;
   if (pretemp==temp)  curnum++;
   else
   {printf("%c/t%d/n",pretemp,curnum);
   pretemp=temp;
   curnum=1;
   }

        }while(!feof(fp));
    fclose(fp);
    fclose(pNewFile);
}
 

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像