通过其他功能更新文件指针

时间:2016-11-23 08:42:08

标签: c

#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);
}

我想通过sf函数将文件指针log更改为指向文件hello,但printf仍在打印prac.txt文件的内容。

5 个答案:

答案 0 :(得分:3)

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

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");
  }
}

答案 1 :(得分:2)

void hello(FILE *fp)中,fp仅存在于函数hello的范围内(当您调用函数时,指针的值被复制,并且在函数结束时被销毁) )。

这有效:

#include<stdio.h>

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

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

    if (sf != NULL) 
    {
        p=fgetc(sf);
        printf("%c",p);
    }
}

答案 2 :(得分:0)

你应该在重新加载之前关闭文件

from example.user import User

答案 3 :(得分:0)

这是因为你复制了参数。您不会仅覆盖文件指针的内容而只覆盖该地址的本地副本。

文件指针本身未更新。要归档这个,要么传递指向函数的指针并相应地取消引用,要么返回新文件指针并覆盖旧文件指针。无论如何都要关闭文件。

答案 4 :(得分:0)

#include<stdio.h>
// Use double pointer since fp is getting address of a pointer variable
void hello(FILE ** fp)
{ 
    // If the file is already pointing to some file then close that file
    if(*fp != NULL)
    {
        fclose(*fp); 
        *fp = NULL;
    }
    if( ( *fp = fopen("log","r") ) == NULL)
        printf("%s", "Error opening file");
}

int main()
{
    char p;
    FILE *sf=fopen("prac.txt","r");
    // While sending the file pointer you need to send the address of the file pointer
    hello(&sf);

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

    return 0;
}