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

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

本文介绍了如何从C中的文本文件读取数字块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

试用Gunner提供的解决方案:

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?

推荐答案

我为此编写了一个程序


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

这篇关于如何从C中的文本文件读取数字块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:55