尝试从文件读取行返回错误的行

时间:2019-09-08 09:08:26

标签: c file io

从C中的文件读取一行时,尝试使用printf时返回错误的行。我认为这是因为我返回的是char *而不是char,但是返回char会导致崩溃。

char* getLineFromFile(const char name[], int lineNumber) 
{
    FILE *file = fopen(name, "r");
    int count = 0;
    if (file != NULL)
    {
        char line[256]; /* or other suitable maximum line size */
        while (fgets(line, sizeof line, file) != NULL) /* read a line */
        {
            if (count == lineNumber)
            {
                fclose(file);
                return line;
            }
            else
            {
                count++;
            }
        }
        fclose(file);
    }
    else
    {
        printf("Couldn't find file!");
    }
}

//Example call
printf(getLineFromFile("Include/index.db", 1));

应该获取文件的第二行,但返回格式错误的字符串。

1 个答案:

答案 0 :(得分:1)

问题是return line;中的getLineFromFile-您返回local array并尝试通过调用printf来访问未定义行为。相反,将缓冲区传递到getLineFromFile并在找到行时将其复制到其中:

int getLineFromFile(const char name[], int lineNumber, char* out, size_t outsize)
{
    FILE* file = fopen(name, "r");
    int count = 0;
    if (file != NULL)
    {
        char line[256]; /* or other suitable maximum line size */
        while (fgets(line, sizeof line, file) != NULL) /* read a line */
        {
            if (count == lineNumber)
            {
                fclose(file);
                strncpy(out, line, outsize);
                out[outsize - 1] = '\0';
                return 1;
            }   
            else
            {
                count++;
            }
        }
        fclose(file);
        return 0;
    }
    else
    {
        printf("Couldn't find file!");
        return 0;
    }
}

//Example call
char lineBuffer[256];
if (getLineFromFile("Include/index.db", 1, lineBuffer, sizeof lineBuffer)) {
    printf("%s", lineBuffer);
}