에 대해 fgets()
검사와 오류를 확인하려면 아니라고 이상 40.then 쇼 malloc()
문자열을 반환하기 위해 반복적으로 fgets()
을 사용하는 함수를 작성하기 쉽습니다.
이 함수는 적절한 오류보고를 수행하지 않습니다. realloc()
또는 fgets()
을 사용하여 오류가 발생하면 지금까지 검색된 데이터가 반환됩니다.
외에도이 기능은 꽤 유용합니다.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * read_one_line(FILE * in)
{
size_t alloc_length = 64;
size_t cumulength = 0;
char * data = malloc(alloc_length);
while (1) {
char * cursor = data + cumulength; // here we continue.
char * ret = fgets(cursor, alloc_length - cumulength, in);
printf("r %p %p %zd %zd %zd\n", data, cursor, cumulength, alloc_length, alloc_length - cumulength);
if (!ret) {
// Suppose we had EOF, no error.
// we just return what we read till now...
// there is still a \0 at cursor, so we are fine.
break;
}
size_t newlength = strlen(cursor); // how much is new?
cumulength += newlength; // add it to what we have.
if (cumulength < alloc_length - 1 || data[cumulength-1] == '\n') {
// not used the whole buffer... so we are probably done.
break;
}
// we need more!
// At least, probably.
size_t newlen = alloc_length * 2;
char * r = realloc(data, newlen);
printf("%zd\n", newlen);
if (r) {
data = r;
alloc_length = newlen;
} else {
// realloc error. Return at least what we have...
// TODO: or better free and return NULL?
return data;
}
}
char * r = realloc(data, cumulength + 1);
printf("%zd\n", cumulength + 1);
return r ? r : data; // shrinking should always have succeeded, but who knows?
}
int main()
{
char * p = read_one_line(stdin);
printf("%p\t%zd\t%zd\n", p, malloc_usable_size(p), strlen(p));
printf("%s\n", p);
free(p);
}
그러나 예를 들어 표준 입력란이 45 문자 인 경우. 이 경우에는 40 문자를 얻고 자르기보다는 오류 메시지를 넣고 싶습니다. 내가 어떻게 그럴 수 있니? –
@JakobAbfalter 아마도 당신은'fgets'의 버전을 쓰고, 입력을 문자로 받아 들여서 C 문자열을 만들 필요가 있습니다. char의 수가 최대 크기보다 커지면 메시지를 출력 할 것입니다. 또한 안전하지 않고 버퍼 오버플로에 취약하기 때문에'gets '를 제안하지 않을 것입니다. – P0W