[英]Reading integers from txt file in C
我正在制作一个文件读取器,该文件读取器从文件中逐行读取整数。 问题是那不起作用。 我认为我以错误的方式使用fscanf。 有人能帮我吗?
我已经在其他问题中寻找答案,但是找不到任何能解释为什么我的代码无法正常工作的答案。
int read_from_txt(){
FILE *file;
file = fopen("random_numbers.txt", "r");
//Counting line numbers to allocate exact memory
int i;
unsigned int lines = 0;
unsigned int *num;
char ch;
while(!feof(file)){
ch = fgetc(file);
if (ch == '\n'){
lines++;
}
}
//array size will be lines+1
num = malloc(sizeof(int)*(lines+1));
//storing random_numbers in num vector
for(i=0;i<=lines;i++){
fscanf(file, "%d", &num[i]);
printf("%d", num[i]);
}
fclose(file);
}
txt文件类似于:
12
15
32
68
46
...
但是此代码的输出始终给出“ 0000000000000000000 ...”
您忘记了“倒带”文件:
fseek(file, 0, SEEK_SET);
您的读取过程将遍历文件两次-一次计数行,再一次读取数据。 您需要在第二遍之前返回文件的开头。
请注意,您可以通过以下方式一次性使用realloc
:在循环中将数字读入一个临时int
,对于每次成功的读取,通过调用realloc
将num
数组扩展一个。 这将根据需要扩展缓冲区,并且您无需倒带。
在重新分配给num
之前,请仔细检查realloc
的结果,以避免内存泄漏。
您可以尝试使用标准IO中的getline
函数,然后仅使用一个循环就将解析后的数字添加到数组中。 请参见下面的代码。 请检查https://linux.die.net/man/3/getline
另外,您可以使用atoi
或strtoul
函数将读取的行转换为整数。 随时检查https://linux.die.net/man/3/atoi或https://linux.die.net/man/3/strtoul
下面的代码对带有数字列表的文件求值,并将这些数字添加到C整数指针中
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char ** argv) {
FILE * file;
file = fopen("./file.txt", "r");
size_t read;
char * line = NULL;
size_t line_len = 0;
size_t buffer_size = 10;
int * buffer = (int *)malloc(sizeof(int) * buffer_size);
int seek = 0;
while((read = getline(&line, &line_len, file)) != -1) {
buffer[seek++] = atoi(line);
if (seek % 10 == 0) {
buffer_size += 10;
buffer = (int *)realloc(buffer, sizeof(int) * buffer_size);
}
}
for (int i = 0; i < seek; i++) {
printf("%d\n", buffer[i]);
}
free(buffer);
fclose(file);
}
如果您不确定应该使用哪个转换功能。 您可以在以下位置检查atoi
和sscanf
之间的区别:sscanf或atoi将字符串转换为整数的区别是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.