【发布时间】:2020-04-10 03:43:54
【问题描述】:
是的,看到了许多与此类似的问题,但想尝试以我的方式解决它。运行后获取大量文本块(编译正常)。
我试图从文件中获取未知大小的字符串。考虑分配大小为 2 的 pts(1 个字符和空终止符),然后使用 malloc 为每个超过数组大小的字符增加 char 数组的大小。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *pts = NULL;
int temp = 0;
pts = malloc(2 * sizeof(char));
FILE *fp = fopen("txtfile", "r");
while (fgetc(fp) != EOF) {
if (strlen(pts) == temp) {
pts = realloc(pts, sizeof(char));
}
pts[temp] = fgetc(fp);
temp++;
}
printf("the full string is a s follows : %s\n", pts);
free(pts);
fclose(fp);
return 0;
}
【问题讨论】:
-
有趣的问题,但究竟是什么问题?如果你想得到一个未知大小的字符串,结果是一大块文本,那不成功吗?听起来你把整个文件都读给我听了。
-
此时 -
strlen(pts)你不知道pts里面是什么,你在它上面调用strlen()从而导致 UB。也许calloc()会是更好的选择? -
最坏情况,字符串与文件大小相同;你能分配这么多内存吗?
-
pts = realloc(pts, sizeof(char))不会扩展缓冲区,但总是分配 1 个字节。您必须指定 total 长度 -
每次执行时会发生什么:
while (fgetc(fp) != EOF) {?从文件中读取了一些内容,但它去了哪里?
标签: c string file string-length fgetc