gpt4 book ai didi

c - 通过其他函数更新文件指针

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:25 25 4
gpt4 key购买 nike

#include<stdio.h>

void hello(FILE * fp)
{
if( ( fp = fopen("log","r") ) == NULL)
printf("%s", "Error opening file");
}

void main()
{
char p;
FILE *sf=fopen("prac.txt","r");
hello(sf);

p=fgetc(sf);
printf("%c",p);
}

我想通过 hello 函数将文件指针 sf 更改为指向文件 logprintf 是仍然打印 prac.txt 文件的内容。

最佳答案

如果你想改变FILE*指向的内容,你需要传递一个FILE**。在更改它之前,您需要确保它恰好指向的任何文件都已关闭。这也依赖于您总是在 fclose 之后将 FILE* 变量设置为 NULL(唉,这不会自动发生),因此很可能粗心地使用此函数在已经关闭的 FILE* 上调用 fclose。但这可能仍然比故意泄漏文件描述符而不刷新文件要好。

void hello(FILE **fp)
{
// This is actually a horrible test. And in general, this is not
// something you should do, but it is better than leaking open
// file descriptors, so, yeah,
if (*fp != NULL) {
fclose(*fp);
*fp = NULL;
printf("Closed file.");
}
if( (*fp = fopen("log","r") == NULL) {
printf("%s", "Error opening file");
}
}

关于c - 通过其他函数更新文件指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40759555/

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