c语言读取该文件内的数据
采集了一系列数据(数据信号,由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);
}
- 上一篇:没有了
- 下一篇:没有了