读取文件流并将其打印在屏幕上的函数调用未定义的行为,我无法定位原因。如果加载了少于两行的文件,则此方法有效,否则它将崩溃。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <inttypes.h>
char *getText (FILE* fp)
{
uint_64 size;
uint_64 i = 0;
int chr;
char *source;
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
source = calloc(size + 1, sizeof(char));
fseek(fp, 0, SEEK_SET); // rewind
while(chr != EOF)
source[i++] = (chr = fgetc(fp));
source[size] = ' '; // Terminate string
return(source);
}
int main(void)
{
char sfile [256];
FILE* fp;
char *file;
char buff [256];
printf("Enter name of file: ");
scanf("%s", sfile);
if(!strncmp(sfile, "read-", strlen("read-")))
{
fp = fopen(sfile + strlen("read-"), "r");
file = getText(fp);
sprintf(buff, file);
printf(buff);
fclose(fp);
free(file);
}
return 0;
}
删除不相关的文件名检查后,当输入文件大小> 256 字节时,程序崩溃,因为
char buff [256];
...
file = getText(fp);
...
sprintf(buff, file);