简体   繁体   English

从txt文件中读取的C中的int数未知

[英]Read from txt file with unknown numbers of int in C

I have to read "N" int from .txt file and place each one to an array X[i] But the problem is, I'm not suposed to know how many int are in the txt. 我必须从.txt文件中读取“ N” int并将每个int放置到数组X [i]中,但问题是,我不愿知道txt中有多少个int。 The code has to work for every txt following this model 该代码必须适用于遵循此模型的每个txt

5 4 5 4
1 2 3 1 2 3
1 3 4 1 3 4
2 3 5 2 3 5
4 5 5 4 5 5

So I have, in the first line, the second number (4 in the exemple) the number of int in the txt will be N=4*3 (4 lines with 3 numbers (ALWAYS second number*3)) + 2 (first line) 所以我在第一行中有第二个数字(例如4),txt中的int数将为N = 4 * 3(4行包含3个数字(总是第二个数字* 3))+ 2(第一个线)
The only code I know how to do is when I know how much numbers, like 我知道怎么做的唯一代码是当我知道有多少个数字时,例如

    int t[14] // I know there are 14 numbers on the .txt
    while(fgets(buf, sizeof(buf), fp)) {

  int result = sscanf(buf, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d", &t[0], &t[1], &t[2], &t[3], &t[4], &t[5], &t[6],&t[7],&t[8],&t[9],&t[10], &t[11],&t[12],&t[13]);
  if (result <= 0) break;  // EOF, IO error, bad data

  for (r=0; r<result; r++) {
    if (i >= sizeof(X)/sizeof(X[0])) break;  // too many
    X[i++] = t[r]; //put them in the X[MAX]
  }
}  

And I need to read every number cause like in 我需要阅读每个数字原因,例如
2 3 5 2 3 5
I'll place 5 to a array[2][3] 我将5放置到数组[2] [3]
How I am supposed to do this? 我应该怎么做? Can someone show me an example??? 有人可以给我举个例子吗? Thanks! 谢谢!

A simple template: 一个简单的模板:

int a, b, i;
int *N;
if(fscanf(fp, "%d%d", &a, &b) != 2) { /* Read the first 2 integers */
    /* Unable to read in 2 integers. Handle error... */
}
N = malloc(3 * b * sizeof(int)); /* Allocate enough space */
for(i = 0; i < 3*b; ++i) {
    if(fscanf(fp, "%d", &N[i]) != 1) { /* Read numbers one-by-one */
        /* Input may not be enough. Handle error... */
    }
}
/* Now you have (3*b) integers stored in N */
/* after operations completed... */
free(N);

There is no need to read in line-by-line and guess how many numbers are there. 无需逐行阅读并猜测有多少个数字。 Just call fscanf() again and again since your input is delimited by space characters and newline characters. 只需一次又一次调用fscanf() ,因为您的输入由空格和换行符分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM