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

时间:2011-03-11 07:29:35

标签: c file

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

尝试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++; }
}

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

2 个答案:

答案 0 :(得分:1)

继续读取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++;
}

答案 1 :(得分:1)

我为此编写了一个程序

read data from input file line-by-line
keep a line count
based on the current line count copy the line to a specific output file

类似这样的事情

#include <stdio.h>
#include <stdlib.h>

#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;
}