英文:
file pointer is changing to NULL when fread last line in c
问题
我有一个包含5个长整数的二进制文件,一切都按预期运行,但是当我读取文件中的最后一项时,文件指针从func2返回NULL,在func2的末尾文件指针仍然不为NULL,但当我回到func1时,我看到它变成了NULL,你能帮我理解为什么吗?
这是两个函数:
long int * func1(char * filename, int numOflogInts)
{
long int numbers[5];
FILE* fp = fopen(filename, "rb");
for (int i = 0; i < numOflogInts; i++) {
numbers[i] = func2(fp, i);
}
return numbers;
fclose(fp);
}
long int func2(FILE * fp, int place)
{
long int num;
fseek(fp, sizeof(long int) * place, SEEK_SET);//跳到指定位置
fread(&num, sizeof(long int), 1, fp);
return num;
}
希望这有助于解决你的问题。
英文:
I have a binary file with 5 long ints, everything working as expected but when I read the last item in the file the file pointer return NULL from func2 and int the end of func2 filepointer is still not null but when im back to func1 I see it became naull,can you please help me understand why?
this is the 2 functions:
long int * func1(char * filename, int numOflogInts)
{
long int numbers[5];
FILE* fp = fopen(filename,"rb");
for (int i = 0; i < numOflogInts; i++) {
numbers[i] = func2(fp, i);
}
return numbers;
fclose(fp);
}
long int func2(FILE * fp, int place)
{
long int num;
fseek(fp, sizeof(long int) * place, SEEK_SET);//skip to the place
fread(&num, sizeof(long int), 1, fp);
return num;
}
答案1
得分: 1
一些错误:
- 你返回了一个在栈上需要分配的数组的地址。在此之后使用它会导致未定义的行为。
- 同样在
func1
中,你返回了,然后关闭了文件指针。但是由于返回语句,这个fclose
调用是无法到达的。 - 你使用了常量
5
,而没有使用numOflogInts
来确定数组的大小。你的循环表明这不是正确的做法。
为了解决第一个问题,动态地分配你的数组。为了修复第二个问题,在返回之前关闭文件。
long int * func1(char * filename, int numOflogInts)
{
long int *numbers = malloc(sizeof(long int) * numOflogInts);
FILE* fp = fopen(filename, "rb");
if (numbers == NULL || fp == NULL) {
// Handle error here, e.g., by returning NULL or taking appropriate action.
// 处理错误,例如通过返回 NULL 或采取适当的操作。
}
for (int i = 0; i < numOflogInts; i++) {
numbers[i] = func2(fp, i);
}
fclose(fp);
return numbers;
}
当然,你还需要检查内存分配和文件打开时的错误。
英文:
A couple of mistakes:
- You're returning the address of an array that's need allocated on the stack. Using it after this leads to undefined behavior.
- Also in
func1
you've returned, then closed the file pointer. But because of the return, thisfclose
call is unreachable. - You've got a constant
5
, rather than usingnumOflogInts
to determine the size of your array. Your loop suggests this is not the right thing to do.
To address the first issue, dynamically allocate your array. To fix the second, close the file before returning.
long int * func1(char * filename, int numOflogInts)
{
long int *numbers = malloc(sizeof(long int) * numOflogInts);
FILE* fp = fopen(filename,"rb");
for (int i = 0; i < numOflogInts; i++) {
numbers[i] = func2(fp, i);
}
fclose(fp);
return numbers;
}
Of course, you also want to check for errors in both your memory allocation and in opening the file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论