使用 stdlib.h C++ 读取文件

Read files with stdlib.h C++

我在使用 stdlib.h header 使用 C++ 读取文件时遇到了一些问题。请更正我语法中的错误。编译器说'FILE has no member named buffer, curp, fd, and flags'是什么意思?

#include <stdio.h>
#include <stdlib.h>

int main(){
    FILE *fp;

    if ((fp = fopen("text.txt", "w"))==NULL){
        printf("error!");
        exit(1);
    }

    fputs("ABCDE\n", fp);
    printf("file address : %p\n", fp->buffer);
    printf("file size : %d byte \n", fp->bsize);
    printf("file position : %p\n", fp->curp);
    printf("file contents : ");

    for (int i = 0; i <= 4; i++){
        printf("%c", *(fp->buffer+i));
    }

    printf("\n");
    printf("file identity is unknown : %d\n", fp->fd);
    printf("file status : \n");

    if ((fp->flags & 1)==1) printf ("readonly\n");
    if ((fp->flags & 2)==2) printf ("writeonly\n");
    if ((fp->flags & 3)==3) printf ("read/write\n");
    if ((fp->flags & 8)==8) printf ("file line\n");
    if ((fp->flags & 16)==16) printf ("error\n");
    if ((fp->flags & 32)==32) printf ("end of the file\n");
    if ((fp->flags & 64)==64) printf ("binary file\n"); else printf ("file text\n");
    if ((fp->flags & 128)==128) printf ("data from file\n");
    if ((fp->flags & 256)==256) printf ("data from file\n");
    if ((fp->flags & 512)==512) printf ("file is in the terminal\n"); else  printf("file is in the disk");

    fclose(fp);
}

FILE 是不透明类型; C 标准没有定义它的字段,因此它们可以在不同的实现中有所不同。您的程序期望 FILE 类型具有具有特定名称的字段,但您的系统实际上并没有那样定义它。

不要依赖 FILE 具有特定字段,也不要取消引用 FILE* 来尝试访问这些字段。相反,使用 C 标准库提供的函数,例如 fread 读取内容和 ftell 获取当前位置。这些函数采用 FILE* 参数,并以适合程序 运行.

的系统的任何方式访问其内容。