c - 尝试使用 fgetc() 从文件中读取未知字符串长度
问题描述
所以,是的,看到了许多与此类似的问题,但想尝试以我的方式解决它。运行后获得大量文本块(编译良好)。
我试图从文件中获取未知大小的字符串。考虑以 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;
}
解决方案
你可能想要这样的东西:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define CHUNK_SIZE 1000 // initial buffer size
int main()
{
int ch; // you need int, not char for EOF
int size = CHUNK_SIZE;
char *pts = malloc(CHUNK_SIZE);
FILE* fp = fopen("txtfile", "r");
int i = 0;
while ((ch = fgetc(fp)) != EOF) // read one char until EOF
{
pts[i++] = ch; // add char into buffer
if (i == size + CHUNK_SIZE) // if buffer full ...
{
size += CHUNK_SIZE; // increase buffer size
pts = realloc(pts, size); // reallocate new size
}
}
pts[i] = 0; // add NUL terminator
printf("the full string is a s follows : %s\n", pts);
free(pts);
fclose(fp);
return 0;
}
免责声明:
- 这是未经测试的代码,它可能不起作用,但它显示了这个想法
- 为了简洁起见,绝对没有错误检查,您应该添加它。
- 还有其他改进的空间,它可能可以做得更优雅
推荐阅读
- react-native - React Native 中的 Csrf 令牌发布
- excel - 在另一个术语再次出现之后在 VBA 中查找第一次出现的术语
- renjin - 语法错误,意外的符号,在将列表转换为 R 中的 data.frame 时需要“,”
- angular - 填充嵌套数据的最佳方法
- r - 在 R 中使用 for 循环更新向量的问题
- android - 领域:没有索引的 updateOrInsert
- mysql - 使用 DB Facade 仅插入一次 DB
- fat-free-framework - 将多个 VALUES 插入表中
- javascript - 添加指向随机文本的链接
- dotnetnuke - Dotnetnuke 社区安装