-->

How to read blocks of numbers from a text file in

2019-09-19 05:45发布

问题:

I have a file numbers.dat containing about 300 numbers(floating point,negative positive)in column format. The objective is to first fill in numbers.dat with 300 numbers and then extract 100 numbers each time into another file say n1.dat. The second file n2.dat will have the next 100 numbers from numbers.dat and so on for 3 subsets of files obtained from number.dat. I am unable to understand how the location of the last read 100th number is taken into account so that the file read and fetching for the next block occurs after the previos fetched number.

Trying out the Solution provided by 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++; }
}

The problem is only one data is being written. What should be the correct process?

回答1:

I'd write a program for that as

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

something like this

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


回答2:

Continue to read from number.dat and write to the corresponding output file based on the index of current number read.

Sample code.

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


标签: c file