文件指针或流指针背后的概念是什么? [英] What is the concept behind file pointer or the stream pointer?

查看:137
本文介绍了文件指针或流指针背后的概念是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道指针是一个变量,用于存储另一个变量的地址.因此,我了解了char类型指针,整数类型指针的概念,将一个指针添加到指针时会发生什么,等等.但是我没有真正了解文件指针背后的概念.为什么我们不能像字符数据类型那样直接指向它们呢?例如,考虑一个包含内容的文件:

  Hello World极好的 

让'ptr'指向该文件.为什么我们不能使用技术ptr指向'H',(ptr + 1)指向'e',(ptr + 2)指向'l',依此类推.如果我的问题很愚蠢,请原谅,有时候,如果我理解真正的概念,这将变得很清楚.我认为此文件实际上存储在内存中,就像字符串存储在内存中一样.(我知道fscanf()函数和全部)

解决方案

有些东西叫做内存映射文件,但除此之外,您只需打开文件并将其加载到缓冲区(这是从文件中读取数据的常用方式),就可以实现所需的功能(如果我理解正确的话).>

一旦进入内存,您将使用 * buf 访问第一个字节,然后使用 *(buf + 1)访问第二个字节,依此类推;或者,通常更清晰,使用 buf [0] buf [1] 等.

如果不使用内存映射文件,为什么不能呢?由于在C中使用 fopen 打开文件时所拥有的是不透明的指针(即,指向您未知数据的指针,因此必须将其视为概念",而不是实际数据)您可以阅读),允许其他函数(fread,fwrite,fseek等)对打开的文件操作",但该指针不包含"文件的字节.有时称其为 handler 是有原因的:它使处理"文件成为可能.

使用不透明指针 FILE * ,您可以从内存中的文件读取字节,然后可以处理内存中的数据.

I know that pointer is a variable that stores address of another variable. So i understood the concepts of char type pointers, integer type pointers, what happens when we add one to a pointer etc. But i didn't get the real concept behind file pointer. Why can't we directly point to them as we do in case of character data type? For eg consider a file with content:

Hello World
fantastic

Let 'ptr' point to this file. Why can't we use the technique ptr to point to 'H', (ptr+1) to 'e', (ptr+2) to 'l' and so on. If my question is stupid, forgive sometimes it would becomes clear if i understand the real concept. I think this file is actually stored in memory just like a string is stored in memory. (I know fscanf() function and all)

解决方案

There's something called memory mapped file, but this apart, you can achieve what you want (if I understood it correctly) simply opening the file and loading it into a buffer (which is by the way a common way of reading data from files).

Once in memory, you access the first byte with *buf, the second with *(buf+1) and so on; or, usually better since clearer, with buf[0], buf[1] and so on.

Why you can't if you don't use a memory mapped file? Since what you have when you open a file in C (using fopen) is an opaque pointer (i.e. a pointer pointing to data unnknown to you, you must consider it as a "concept" rather than actual data you can read) allowing other functions (fread, fwrite, fseek, and so on) to "operate" on that file you opened, but that pointer does not "contain" the bytes of the file. It is called sometimes handler for a reason: it makes it possibile to "handle" the file.

Using that opaque pointer FILE*, you can read bytes from that file in memory, then you can process the data in memory.

这篇关于文件指针或流指针背后的概念是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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