FILE *infp, *outfp;
infp = fopen(argv[2], "r");
int len;
char *text;
fseek(infp, 0, SEEK_END);
len = ftell(infp);
printf("%dn", len);
if ((text = (char *) malloc(500000000)) == NULL)
{
fprintf(stderr, "Error allocating memoryn");
exit(1);
}
fread(text, len, 1, infp);
text[len] = ' ';
fclose(infp);
printf("Text = %s, Address = %un", text, text);
返回138
Text = , Address = 3794927632
我不知道为什么文本不打印任何东西。我用错词了吗?
您需要像这样重置rewind()
或fseek(3)
的文件位置
FILE *infp;
FILE *outfp;
int length;
char *text;
if ((infp = fopen(argv[2], "r")) == NULL)
{
fprintf(stderr, "Error openning `%s'n", argv[2]);
return -1;
}
fseek(infp, 0L, SEEK_END);
len = ftell(infp);
/* reset position */
fseek(infp, 0L, SEEK_SET); /* essentially rewind(infp); */
printf("%dn", length);
if ((text = malloc(length + 1)) == NULL)
{
fprintf(stderr, "Error allocating memoryn");
return -1;
}
if (fread(text, 1, length, infp) == length)
{
text[length] = ' ';
printf("Text = %s, Address = %un", text, text);
free(text); /* never forget to `free' */
}
else
{
free(text);
text = NULL:
}
fclose(infp);
你也应该
- 检查
fopen()
的返回值,您从未检查文件是否实际打开,我认为这是主要问题。 - 只分配必要的空间
- 确保
fread()
不失效 交换
fread(3)
的size参数,首先是元素的大小,然后是元素的个数size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
和返回值应该等于
nmemb
,阅读上面链接的手册页
After
fseek(infp, 0, SEEK_END);
infp
指向文件的末尾。你需要倒带文件。
rewind(infp);