我正在读取一个文件,并将文件中的字符单独存储到数组中。 我的问题是:在读取文件时,如何在读取新行之前向数组插入 10 个元素。
示例:
File:
471 22 01 05 34 75 78 65 46 34 20 19
521 01 02 03 45 35 42 36 87 99 12 23 12 37 64
当我读取文件时,它应该像这样结束:
[V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,22,01,05,34,75,78,65,46,34,20,19,V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,01,02,03,45,35,42,36,87,99,12,23,12,37,64]
我目前的想法是:
在开始读取文件之前,我已经将前 10 个元素插入到数组中。然后在读取文件时,每当我找到“\0”时,我都会使用循环再次插入变量,这就是我得到的:
Elements = [V0,V1,V2,V3,V4,V5,V6,V7,V8,V9];//array of elements to insert
int i = 0;
int j = 0;
//this loop reads the file and ignores what's not necessary(it's working properly)
while(s2[i] != '\0')//reading chars from the file
{
if(s2[i] == ' ')
i++;
MEM[j]=atoi((s2+i));//MEM is the array in which i'm storing the lines
i += 3;//increment by 3 due to problem specifics(needs to ignore the first 3 values from the file)
j++;
}
我知道我的想法不是很有效,但我是 C 新手,我不知道如何正确地做到这一点。
有谁知道更好的方法吗? 谢谢
最佳答案
如您所示,输入文件包含
471 22 01 05 34 75 78 65 46 34 20 19
521 01 02 03 45 35 42 36 87 99 12 23 12 37 64
您可以使用 fscanf()
逐字读取,而不是逐个字符读取,因为显示的文件由相似的类型组成(全部是数字)。来自 fscanf()
的手册页。
int fscanf(FILE *stream, const char *format, ...);
每次调用realloc()
读取一一整数并分配动态内存,在这种情况下您无需担心数组的大小。以下是从文件读取数据并将数据存储到整数数组中的示例代码。
int main(void) {
FILE *fp = fopen("input.txt","r");
if(fp == NULL){
/*.. error handling */
return 0;
}
int row = 1;
int *input = malloc(sizeof(*input));/*1st time 4 byte, to store first integer inside file */
/* here input is dynamic array */
while(fscanf(fp,"%d",&input[row-1]) == 1) { /* fscanf() read upto whitespace at a time */
row++;
input = realloc(input,row * sizeof(*input));/* reallocate based on number of input */
}
for(int index = 0 ; index < row-1 ;index++) {
printf("%d\n",input[index]);
}
/* free dynamically allocated memory @TODO*/
return 0;
}
关于c - 读取文件并在每行的开头添加 10 个数组元素读取到数组我正在存储文件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305686/