我有这个函数,它读取某个 .txt 文件的第一行并返回该行供我使用。我不知道这条线有多长,所以我不能有恒定大小的缓冲区。 我的问题是我无法使用此功能,因为它不是我的代码,因此会被视为作弊(我有考试)。
我一直在考虑数组的可变长度,但正如对我所说的那样,它是邪恶的,我可以在我猜的某个地方扫描整行,但我不确定在这种情况下我该怎么做(我需要返回线)
char* readLine(FILE *line) {
char individualChar;
int pos = 0;
int size = 16;
char *buffer = (char *)malloc(size);
while ((individualChar = fgetc(line)) != EOF && individualChar != '\n'){
if (pos + 1 == size){
size *= 2;
char *tmp = (char *)realloc(buffer, size);
if (!tmp){
free(buffer);
fprintf(stderr, "Realloc failed");
return 0;
}
buffer = tmp;
}
buffer[pos] = individualChar;
pos++;
}
buffer[pos] = '\0';
return buffer;
}
最佳答案
在这里发布太多代码并不像 OP 那样好
considered as cheating (I have my exams) because of it is not my code.
一些小技巧
I do NOT know how long is the line going to be so I can not have constant size of buffer.
防御性编程假定一个合理的合理上限以防止黑客攻击。 IAC,读取文本文件会受到环境限制。
Environmental limits
An implementation shall support text files with lines containing at least 254 characters, including the terminating new-line character. The value of the macroBUFSIZ
shall be at least 256. C11 §7.21.2 7
采用这种方法:
#include <stdio.h>
#define SANE_BOUND (BUFSIZ+1)
char* readLine(FILE *line) {
char buffer[SANE_BOUND];
if (fgets(buffer, sizeof buffer, line) == NULL) {
return NULL;
}
return strdup(buffer);
}
How to simplify this
readLine()
function?
明确地说,您不想复制的代码有问题。
更正
// char is insufficient to distinguish the 257 different results from fgetc()
// char individualChar;
int individualChar;
// Use size_t for sizing, `int` may be too small
size_t pos = 0;
size_t size = 16;
应该先fgetc()
回电EOF
或稍后调用返回 EOF
由于罕见的输入错误,该函数应返回 NULL
.
放弃强制转换,不需要。
//char *buffer = (char *)malloc(size);
//char *tmp = (char *)realloc(buffer, size);
char *buffer = malloc(size);
char *tmp = realloc(buffer, size);
为什么检查不完整?
代码有if (!tmp){
但没有事先检查 if (!buffer){
轻微
// Use \n and stay case correct
// fprintf(stderr, "Realloc failed");
fprintf(stderr, "realloc() failed\n");
迂腐
size *= 2;
可能溢出。您希望安全到什么程度?
设计
我希望 合适的尺寸 最后一个 realloc()
.
我会重新设计以将读取的大小和分配的内存都传回给调用者。文本文件 行 不常见地可能包含 空字符 并且仅返回一个 string 指针并不能传达某些内容已被读取。适用于此case也是。
一个好的分配readLine()
将不如 OP 的发布代码简单。
关于c - 如何简化这个 readLine() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56283458/