首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C逐行读取文件

C逐行读取文件
EN

Stack Overflow用户
提问于 2010-08-17 18:08:59
回答 11查看 1M关注 0票数 230

我编写此函数是为了从文件中读取一行:

代码语言:javascript
复制
const char *readLine(FILE *file) {

    if (file == NULL) {
        printf("Error: file pointer is null.");
        exit(1);
    }

    int maximumLineLength = 128;
    char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);

    if (lineBuffer == NULL) {
        printf("Error allocating memory for line buffer.");
        exit(1);
    }

    char ch = getc(file);
    int count = 0;

    while ((ch != '\n') && (ch != EOF)) {
        if (count == maximumLineLength) {
            maximumLineLength += 128;
            lineBuffer = realloc(lineBuffer, maximumLineLength);
            if (lineBuffer == NULL) {
                printf("Error reallocating space for line buffer.");
                exit(1);
            }
        }
        lineBuffer[count] = ch;
        count++;

        ch = getc(file);
    }

    lineBuffer[count] = '\0';
    char line[count + 1];
    strncpy(line, lineBuffer, (count + 1));
    free(lineBuffer);
    const char *constLine = line;
    return constLine;
}

函数正确地读取了文件,并且使用printf我看到constLine字符串也被正确地读取了。

但是,如果我像这样使用函数:

代码语言:javascript
复制
while (!feof(myFile)) {
    const char *line = readLine(myFile);
    printf("%s\n", line);
}

printf输出胡言乱语。为什么?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3501338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档