gpt4 book ai didi

c - 将文本文件中的数字数组读取到 C 中的数组中

转载 作者:行者123 更新时间:2023-11-30 18:15:17 25 4
gpt4 key购买 nike

这是写入文本文件 ex 的内容。 “123.txt”:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 

如何将这些数字放入数组中?

我的想法:

  1. 打开文件(当然)

  2. 使用某种形式的 fscanf

  3. 将 fscanf 置于循环下,并随着循环的进行将数字分配给新数组

  4. 关闭文件

任何关于如何做到这一点的想法都非常感谢。感谢您抽出时间。

编辑1:

注意,出于严格学习的目的,我在这个问题上考虑了效率问题。此外,错误检测是隐含的,但不包括在内。

int* load( const char* filename ) {
int i;
len = 100; // How to find len of array?
array[len];
FILE* fp = fopen( filename, "r" )

while( !feof(fp) ) {
fscanf(fp,"%d, ",&array[i]);
i++;
}
fclose(f1);
return array;

我的循环代码没有结束。

最佳答案

scanf 函数通常非常慢。我会使用 fread 和 strtok。

stat file get size
allocate buffer
fread to buffer
while not end of buffer
strtok
array[index] = strtoul(buf, 0, 10)
loop

手册页链接上 strtok 的好例子 http://man7.org/linux/man-pages/man3/strtok.3.html

关于c - 将文本文件中的数字数组读取到 C 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35739883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com