C 为什么可以';我不能把文件读入缓冲区吗?

C 为什么可以';我不能把文件读入缓冲区吗?,c,C,我有一个非空文件(list.txt),我正试图读入缓冲区(缓存),然后将缓冲区打印到标准输出。我尝试了下面三种不同的方法,但都没有成功 FILE *list; char *cache; long size; list = fopen("list.txt", "rb"); //open list.txt for reading if (list==NULL) { perror ("Error opening file"); exit(3); } fseek(list

我有一个非空文件(list.txt),我正试图读入缓冲区(缓存),然后将缓冲区打印到标准输出。我尝试了下面三种不同的方法,但都没有成功

FILE *list;
char *cache;
long size;

list = fopen("list.txt", "rb"); //open list.txt for reading

if (list==NULL) {
    perror ("Error opening file"); 
    exit(3);
    }

fseek(list, 0, SEEK_END);
if (ftell(list) == 0){
    fprintf(stdout, "list.txt is empty \n");
}

//three different methods - none seem to work. 
while(fgets(cache, sizeof(cache), list)) {}    //method 1
fprintf(stdout, "cache is %s\n", cache);

fgets(cache, sizeof(cache), list);             //method 2
fprintf(stdout, "cache is %s\n", cache);

if (fread(cache, size, 1, list) == 1){         //method 3
    fprintf(stdout, "successful fread: cache = %s\n", cache);
    }
我的输出如下:

cache is (null)
cache is (null)
我保证我的文件存在并且不是空的。如何才能在该缓冲区中获取文件内容???

您尚未将内存分配给
char
指针
缓存
。在
fgets
中使用它之前,先为它分配内存(还记得
释放它)

注意-方法3中的变量
size
未初始化,因此方法3没有工作的机会。

您没有为
char
指针
缓存分配内存。在
fgets
中使用它之前,先为它分配内存(还记得
释放它)

注意-方法3中的变量
size
未初始化,因此方法3没有工作的机会

  • 您不为缓存分配内存。使用ftell()result是个好主意
  • 您使用“sizeof(缓存)”。请注意,这只是指针的大小-4或8字节
  • 您不为缓存分配内存。使用ftell()result是个好主意
  • 您使用“sizeof(缓存)”。请注意,这只是指针的大小-4或8字节

  • 问题1

    fseek(list, 0, SEEK_END);
    
    列表
    置于文件末尾。您需要倒带文件才能读取其内容

    在读取文件内容之前

    问题2

    在读入
    缓存之前,还需要为其分配内存

    问题3

    fgets
    只读取一行文本。如果要读取整个文件的内容,需要使用
    fread


    尝试:


    问题1

    fseek(list, 0, SEEK_END);
    
    列表
    置于文件末尾。您需要倒带文件才能读取其内容

    在读取文件内容之前

    问题2

    在读入
    缓存之前,还需要为其分配内存

    问题3

    fgets
    只读取一行文本。如果要读取整个文件的内容,需要使用
    fread


    尝试:


    字符*;是指针。您没有为此分配内存。SEEK_END将带您到文件的末尾。使用倒带();您正在读取
    缓存所指向的内存空间;告诉我,
    cache
    指向什么?char*;是指针。您没有为此分配内存。SEEK_END将带您到文件的末尾。使用倒带();您正在读取
    缓存所指向的内存空间;告诉我,
    cache
    指向什么?
    fseek(list, 0, SEEK_END);
    long size = ftell(list);
    if (size == 0)
    {
       fprintf(stdout, "list.txt is empty \n");
    }
    
    // Rewind the file
    rewind(list);
    
    cache = malloc(size+1);
    if ( cache == NULL }
    {
       // Unable to allocate memory.
       exit(1);
    }
    
    int n = fread(cache, 1, size, list);
    if ( n != size )
    {
       // Was able to read only n characters,
       // not size characters.
       // Print a message.
    }
    
    cache[n] = '\0';
    fprintf(stdout, "cache is %s\n", cache);