你好,这是我的问题
FILE *sourcefile;
if ((sourcefile = fopen(argv[1],"r")) == NULL) //Opens File
{
printf("Error: Could not open %sn",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 memoryn");
return 0;
}
printf("%dn",sizeof(buffer));
printf("%dn",fSile);
fread (buffer,1,fSize,sourcefile);
fclose (sourcefile);
我的代码只是打开一个文件并将其内容加载到内存中。问题是,当我使用
时char *buffer = (char *) malloc(fSize)
只分配4个字节而不是文件的完整大小(即打开带有小句子的简单TXT时为25字节)。当我在最后打印buffer
和fSize
的尺寸时,我分别得到4和25,所以fSize
是正确的。知道为什么会这样吗?
谢谢,
sizeof(buffer)
在32位平台上应为4字节。它是一个指向malloc分配的缓冲区的指针。没有办法查询缓冲区的大小
sizeof(buffer)是指针的大小或32位(4字节)。
这可能就是你想要达到的效果。
#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 %sn",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 memoryn");
return 0;
}
printf("%ldn",sizeof(buffer));
printf("%ldn",fSize);
fread (buffer,1,fSize,sourcefile);
fclose (sourcefile);
return 1;
}