我尝试动态realloc
内存,以便一次读取一个字符的文件。它不是按字符打印缓冲区。看起来fread
函数不会一次推进1个字符。
int main() {
FILE *fp;
char *newBuffer;
char *buffer = malloc(sizeof(char));
int count = 0;
/* Open file for both reading and writing */
fp = fopen("test.txt", "r");
if (!fp) {
exit(99);
}
/* Seek to the beginning of the file */
fseek(fp, SEEK_SET, 0);
/* Read into memory and display the buffer as its read */
while (1) {
newBuffer = (char*)realloc(buffer, (sizeof(char) * (++count)));
if (newBuffer) {
buffer = newBuffer;
buffer += (count - 1);
fread(buffer, sizeof(char), 1, fp);
if (feof(fp)) {
buffer = newBuffer;
break;
}
buffer = newBuffer;
printf(" %s\n", buffer);
} else {
// realloc failed
free(buffer);
exit(1);
}
}
fclose(fp);
free(newBuffer);
return(0);
}
答案 0 :(得分:1)
在将缓冲区用作printf
中的字符串之前,不要将其终止,这是一个问题。
请注意,您可以通过各种方式简化或改进代码:
fseek(fp, SEEK_SET, 0);
之后无需fopen
,FILE已经处于起始位置。请注意,您将参数转换为fseek
:它应该是fseek(fp, 0L, SEEK_SET);
但您很幸运SEEK_SET
#defined为0
。getc
而不是fread(buffer, sizeof(char), 1, fp);
从文件中读取一个字节要简单得多。它允许对文件结尾进行更简单和更好的测试。使用feof()
仅适用于您的示例,因为您只尝试读取单个字节。malloc
,设置buffer to
NULL .
realloc accepts
NULL and behaves like
malloc with such as argument,
免费accepts a
NULL`参数并且什么都不做。malloc
的返回值,也不会转换realloc
。sizeof(char)
为1
:使用sizeof(*buffer)
或完全忽略sizeof。return
表达式括起来。main
原型是int main(void)
这是一个更简单的版本:
int main(void) {
FILE *fp;
char *newBuffer;
char *buffer = NULL;
int count = 0, c;
/* Open file for both reading */
fp = fopen("test.txt", "r");
if (!fp) {
exit(99);
}
/* Read into memory and display the buffer read */
while ((c = getc(fp)) != EOF) {
newBuffer = realloc(buffer, count + 2);
if (newBuffer) {
buffer = newBuffer;
buffer[count++] = c;
buffer[count] = '\0';
printf(" %s\n", buffer);
} else {
// realloc failed
fclose(fp);
free(buffer);
exit(1);
}
}
fclose(fp);
free(buffer);
return 0;
}
答案 1 :(得分:0)
您的printf(" %s\n", buffer);
期望buffer
以'\0'
(null)字符结尾。您的代码没有提供所需的空值。