用C语言读取ASCII文件的数据并输出到另一个文件

2025-02-27 16:13:21
推荐回答(3个)
回答1:

看你提供的例子
第一列不一定是字符串啊
还有个8907
1的一行
试试我这个吧
好用的话给个采纳
不好用就算啦
#include
#include
#define in_file "in.txt"
#define out_file "out.txt"
int main()
{
FILE * in, *out;
double k[5];
char buf[1024], *s;
in = fopen(in_file, "r");
if(in == NULL)
{
printf("can not read file %s\n", in_file);
return -1;
}
out = fopen(out_file, "w");
while(fgets(buf, sizeof(buf), in) != NULL)
{
s = strstr(buf, "VELOCITY");
if(s == NULL) continue;
sscanf(s + 9, "%lf%lf%lf%lf%lf", &k[0], &k[1], &k[2], &k[3], &k[4]);
fprintf(out, "%lf\n", k[4]);
}
fclose(in);
fclose(out);
return 0;
}

回答2:

#include
"stdio.h"
void
main()
{
file*
fin
=
null;//输入文件
file*
fout
=
null;//输出文件
char
c;
fin
=
fopen("readme.txt",
"r");
if(fin
==
null)
{
printf("输入文件打开错误!\n");
return;
}
fout
=
fopen("out.txt",
"w");
if(fout
==
null)
{
printf("输出文件打开错误!\n");
return;
}
c
=
fgetc(fin);
while(c
!=
eof)
{
fputc(c,
fout);
printf("%c",
c);//对于这句来说,如果是非中文,输出到屏幕会有问题的!
c
=
fgetc(fin);
}
fclose(fin);
fclose(fout);
printf("输入输出结束!\n");
}
你自己试试,应该可以的

回答3:

#include
void
main()
{
FILE
*fp,*tp;
float
data[6];
char
buffer[256],title[40];
if
(
fp=fopen("data.txt","r")
)
{
if
(
tp=fopen("mdata.txt","w+")
)
{
while
(
!feof(fp)
)
{
fgets(buffer,255,fp);
sscanf(buffer,"%s%f%f%f%f%f%f",title,&data[0],&data[1],&data[2],&data[3],
&data[4],&data[5]);
sprintf(buffer,"%s
%.4f\n",title,data[4]);
fputs(buffer,fp);
}
fclose(tp);
}
else
printf("无法建立输出文件。\n");
fclose(fp);
}
else
printf("无法打开源数据文件读取。\n");
}