如何从C中的文本文件中读取数字块

我有一个文件numbers.dat包含列格式的大约300个数字(浮点,负数)。 目标是首先使用300个数字填写numbers.dat,然后每次将100个数字提取到另一个文件中,例如n1.dat。 第二个文件n2.dat将包含来自numbers.dat的下一个100个数字,依此类推3个从number.dat获得的文件子集。 我无法理解如何考虑最后读取的第100个数字的位置,以便在preios提取的数字之后读取和获取下一个块的文件。

尝试Gunner提供的解决方案:

FILE *fp = fopen("numbers.dat","r"); FILE *outFile1,*outFile2,*outFile3; int index=100; char anum[100]; while( fscanf(fp,"%s",anum) == 1 ) { if(index==100) { // select proper output file based on index. fprintf(outFile1,"%s",anum); index++; } if(index >101) { fprintf(outFile2,"%s",anum); index++; } } 

问题是只写入一个数据。 什么应该是正确的过程?

我会为此编写一个程序

逐行读取输入文件中的数据
保持一个行数
根据当前行数将行复制到特定的输出文件

这样的事情

 #include  #include  #define INPUTFILENAME "numbers.dat" #define MAXLINELEN 1000 #define NFILES 3 #define LINESPERFILE 100 #define OUTPUTFILENAMETEMPLATE "n%d.dat" /* n1.dat, n2.dat, ... */ int main(void) { FILE *in, *out = NULL; char line[MAXLINELEN]; int linecount = 0; in = fopen(INPUTFILENAME, "r"); if (!in) { perror("open input file"); exit(EXIT_FAILURE); } do { if (fgets(line, sizeof line, in)) { if (linecount % LINESPERFILE == 0) { char outname[100]; if (out) fclose(out); sprintf(outname, OUTPUTFILENAMETEMPLATE, 1 + linecount / LINESPERFILE); out = fopen(outname, "w"); if (!out) { perror("create output file"); exit(EXIT_FAILURE); } } fputs(line, out); linecount++; } else break; } while (linecount < NFILES * LINESPERFILE); fclose(in); if (out) fclose(out); return 0; } 

继续读取number.dat并根据读取的当前数字索引写入相应的输出文件。

示例代码。

 FILE *fp = fopen("numbers.dat","r"); FILE *outFile; int index=0; char anum[100]; // since we are not calculating, we can store numbers as string while( fscanf(fp,"%s",anum) == 1 ) { // select proper output file based on index. fprintf(outFile,"%s",anum); index++; }