【发布时间】:2015-04-30 19:02:44
【问题描述】:
背景:我正在尝试打开一个我更改过的文件并为其所有内容保留足够的堆内存。但是,在将所有文件的内容读入堆内存之前,我正在努力寻找程序结束的解决方案。
最佳猜测:我认为我在堆内存中没有保留足够的字节 ||我将指针转换为错误的类型(目前它是 char 类型),这可能对保留堆内存的方式和数量产生了不利影响。
FILE *fptr3;
void highgest_and_lowest_Jan123(void)
{
int c;
unsigned int i = 0;
char *file;
long int size = 0;
fptr3 = fopen("/Users/sam/Desktop/Altered_AL_Weather_Station.txt", "r+");
if (fptr3 == 0)
{
printf("There was an error creating the file.\n");
exit(0);
}
fseek(fptr3, 0, SEEK_END);
size = ftell(fptr3);
file = (char *) malloc(size * sizeof(char));
if(!file)
{
puts("Not enough memory");
exit(1);
}
fseek(fptr3, 0, SEEK_SET);
do
{
c = fgetc(fptr3);
if ((int)c == EOF)
break;
file[i] = c;
printf("%c", file[i]);
i++;
} while((int)c != EOF);
// pus memory back on the heap
free(file);
}
这是我当前的输出:
但是,我的输出应该是这样的:
【问题讨论】:
-
通过程序调试时会发生什么?哪里失败了?
-
使用
int c;代替char c;fgetc的返回值是int。 -
你为什么要投射
c?fgetc返回一个int,将c声明为int -
@user3386109 我正在使用 unix。
-
while 条件应该在
i < size上终止。尝试输出size并将其与您获得的输出进行比较。