传递给函数时,文件指针的行为会有所不同.为什么? [英] File pointers behave differently when passed to functions. Why?

查看:123
本文介绍了传递给函数时,文件指针的行为会有所不同.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码

void getdata(int *q)
{
   for(int i=0;i<3;++i)
      scanf("%d",q++);
   *q=10;
}

int main()
{
   int *p,a[4];
   p=a;
   getdata(p);
   printf("%d",*p);
   return 0;
}

输出显而易见.

7
8
9
7

但是文件指针不能以相同的方式工作.我正在尝试编写用于将数据追加到文件中的基本代码.

But file pointers dont work the same way. I was trying to write a basic code for appending data into a file.

void getdata(FILE *fp)
{
    char ch;
    while((ch=getchar())!=EOF)
        fputc(ch,fp);
    rewind(fp);
}

void printdata(FILE *fp)
{
    char ch;
    while((ch=fgetc(fp))!=EOF)
        putc(ch,stdout);
}
int main()
{
    FILE *fp1;
    fp1=fopen("music.txt","w+");
    getdata(fp1);
    printf("Text is::\n");
    printdata(fp1);
    fp1=fopen("music.txt","a+");
    printf("\nEnter some more text::\n");
    getdata(fp1);
    printf("\nAfter appending text is::\n");
    printdata(fp1);
    return 0;
}

此代码可以正常工作.但是如果rewind(fp);被删除,它的行为就很奇怪.为什么需要倒带指针?尽管指向同一文件不是函数的fp1fp局部变量,所以不应该像第一个程序那样相互影响?

This code works fine. But if rewind(fp); is removed it acts weird. Why do i need to rewind the pointer? Though pointing to the same file aren't fp1 and fp local to the function and so shouldn't affect each other as in the first program?

推荐答案

让我们看一下FILE结构的可能非常简化的实现.就本示例而言,假设content指向映射到磁盘上文件的内存.

Let's look at a possible very simplified implementation of FILE structure. For the purpose of the example, assume content points to a memory that's mapped to a file on the disk..

typedef struct FILE {
    size_t size;
    size_t cursor;
    uint8_t *content;
} FILE;

int fputc(FILE *f, char c) { size++; return f->content[f->cursor++] = c; }
int fgetc(FILE *f) { return (f->cursor == f->size) ? EOF : f->content[f->cursor++]; }
void rewind(FILE *f) { f->cursor = 0; }

现在,当您调用这些函数时,很明显它们会修改基础对象.完成写入文件后,光标指向最后一个元素,因此如果不使用rewind,则fgetc将立即返回EOF.

Now when you call these functions, it is obvious they modify the underlying object. When you are done writing to the file, cursor points to the last element, so fgetc will return EOF immediately if you don't rewind.

为澄清起见,在调用fopen时,将创建一个存储在某处的单个FILE对象.您无法控制该对象,只需获得指向它的指针即可.如果更易于理解,则可以将此指针(在示例中为fp1)视为文件ID.任何更改都是在FILE对象上完成的,而不是指针/ID本身.

To clarify, when you call fopen you create a single FILE object that is stored somewhere. You have no control over this object, you just get a pointer to it. You can consider this pointer (fp1 in your example) as a file ID if it is easier to understand. Any changes are done on the FILE object, not the pointer/ID itself.

这篇关于传递给函数时,文件指针的行为会有所不同.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆