0

你好这是我的问题

FILE *sourcefile;

if ((sourcefile = fopen(argv[1],"r")) == NULL)  //Opens File
{
    printf("Error: Could not open %s\n",argv[1]);
    return 0;
}

fseek(sourcefile, 0 , SEEK_END);  // Sets file pointer at the end of the file
unsigned int fSize = ftell(sourcefile); // Determines file size by the position of file pointer
fseek(sourcefile, 0 , SEEK_SET); // Sets file pointer at the start of the file

char *buffer = (char *) malloc(fSize); 

if (buffer == NULL)
{
    printf("Error: Not enough system memory\n");
    return 0;
}

printf("%d\n",sizeof(buffer));
printf("%d\n",fSile);

fread (buffer,1,fSize,sourcefile);
fclose (sourcefile);

我的代码只是打开一个文件并将其内容加载到内存中。问题是,当我使用

char *buffer = (char *) malloc(fSize)

它只分配 4 个字节,而不是文件的全部大小(即打开一个带有小句子的简单 txt 时为 25 个字节)。当我打印bufferfSize最后的尺寸时,我分别得到 4 和 25,所以fSize是正确的。知道为什么会这样吗?

谢谢,

4

3 回答 3

4

sizeof(buffer) 在 32 位平台上应该是 4 个字节。它是一个指向 malloc 分配的缓冲区的指针。无法查询缓冲区的大小。

于 2014-05-05T00:37:53.090 回答
0

这可能是您想要实现的目标。

#include <stdio.h>
#include <stdlib.h>
int  main(int argc, char *argv[])
{
    FILE *sourcefile;
    if ((sourcefile = fopen(argv[1],"r")) == NULL)  //Opens File
    {
        printf("Error: Could not open %s\n",argv[1]);
        eturn 0;
    }
    fseek(sourcefile, 0 , SEEK_END);  // Sets file pointer at the end of the file
    unsigned long fSize = ftell(sourcefile); 
    fseek(sourcefile, 0 , SEEK_SET); // Sets file pointer at the start of the file
    fSize -= ftell(sourcefile);  /*This determines file size  */
    char *buffer = (char *) malloc(fSize); 
    if (buffer == NULL)
    {
    printf("Error: Not enough system memory\n");
    return 0;
    }

    printf("%ld\n",sizeof(buffer)); 
    printf("%ld\n",fSize);
    fread (buffer,1,fSize,sourcefile);
    fclose (sourcefile);
    return 1;
}
于 2014-05-05T11:27:44.253 回答
0

sizeof(buffer) 是指针的大小或 32 位(4 字节)。它实际上分配了足够的空间。

于 2014-05-05T00:38:03.083 回答