你好,这是我的问题
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个字节)。当我在最后打印buffer和fSize的尺寸时,分别得到了4和25,所以fSize是正确的。知道为什么会这样吗?
谢谢,
发布于 2014-05-05 00:37:53
在32位平台上,sizeof(buffer)应该是4个字节.它是指向malloc分配的缓冲区的指针。无法查询缓冲区的大小。
发布于 2014-05-05 00:38:03
size of (缓冲区)是指针的大小或32位(4字节)。它实际上是分配足够的空间。
发布于 2014-05-05 11:27:44
这也许就是你想要达到的目标。
#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;
}https://stackoverflow.com/questions/23463223
复制相似问题