c - Fscanf 从文件 C 的中间读取
问题描述
我正在创建一个程序,它从文件中读取数字,获取数字数量,创建一个数组并显示这些数字以及文件中的数字数量。我正在使用 fscanf 从文件中获取数据。我终于让程序编译和输出,但它只读取文件中 10 个数字中的 4 个。如果我增加数字的数量,它仍然只能读取 4 个数字。如果我将数字数量减少到 4 以下,它仍然会尝试读取 4 个数字并从内存中打印随机数。我认为这是一个指针问题,但我还是新手,并不完全理解指针。帮助表示赞赏。
代码:
#include <stdio.h>
#include <stdlib.h>
int ReadSize (FILE*);
void readData(FILE* fp, int size, int* arr1);
int* allocateMemory(int);
int main (int argc, char* argv[])
{
FILE * in = fopen(argv[1], "r"); //Gets file to read
int size = ReadSize(in);
printf("Size: %i\n", size); //Temp Line to Print Size
int *arr1 = allocateMemory(size);
readData(in, size, arr1);
printf("Data: ");
for (int i = 0; i < size; i++)
{
printf("%d, ", arr1[i]);
}
}
int ReadSize(FILE* fp)
{
int size = 0;
fscanf(fp, "%d", &size);
return size;
}
void readData(FILE* fp, int size, int* arr1)
{
int i;
for(i = 0; i < size; i++)
{
fscanf(fp, "%d", &arr1[i]);
}
}
int* allocateMemory(int sz)
{
int *temp = (int*)malloc(sizeof(int)*sz);
return temp;
}
输入文件:
4 2
-1 2
1 2
2 -1
-1 -2
解决方案
我认为您误解了文件格式。您从文件中读取“4”,然后您的循环迭代 4 次:因此是 4 个数字,而不是 10。
但我们只能猜测你应该读什么。
也许是这样的:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
FILE *in;
if ((fp = fopen(argv[1], "r")) == 0) {
printf("Error: unable to open file!\n");
return -1;
}
int nitems, items_per_line;
if (fscanf(fp, "%d %d", &nitems, &items_per_line) != 2) {
printf ("Error reading dimensions!\n");
return -1;
}
int *arr1 = malloc (sizeof(int) * nitems * items_per_line);
if (arr1 == 0) {
printf("Error: unable to malloc array!\n");
return 1;
}
for (int i = 0; i < nitems * items_per_line; i++) {
fscanf(fp, "%d", &arr1[i]);
}
return 0;
}
或者,也许您最好使用 n 维数组(例如 arr1[2][4])?
再次 - 在不了解格式的情况下,我们只能猜测......
PS:您应该始终检查代码中的错误!
推荐阅读
- javascript - 如何根据 Pint 的单位和前缀构建自动完成页面字段
- jquery - 如果 Jquery 中的元素不在另一个元素内,则以该元素为目标
- pine-script - 使 Pinescript 指示器仅显示在当前会话中
- python - 将 Pulsar 和 Python 组合成 docker-compose.yaml
- jquery - 在laravel 8中使用jquery ajax重定向到具有会话值的新页面
- html - 仅覆盖一半底部和一半右侧的图像边框
- flutter - 颤振中没有主机的路由
- django - URL 查找不适用于更新和检索
- excel - 使用 VBA 过滤和移动数据
- standardization - 使用 for 循环标准化数据框