首页 > 解决方案 > 从文件中读取行直到换行并将其存储在字符数组中

问题描述

我正在尝试编写一个程序,该程序从文件中读取一行并将其存储到 char 数组中。由于我只想阅读一行,因此我希望它在换行处停止阅读。我当前的代码并没有完全达到我想要的效果。从包含以下内容的文件中:

Hello
u 

我想存储Hello在一个字符数组中。我当前的代码只存储llo和其他一些垃圾。这是我到目前为止所拥有的:

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char random[100];

    FILE *fp;
    fp = fopen("testing.txt", "r");
        if(fp == NULL){
            printf("Can't open the file\n");
            exit(1);
    }

    char c;

while((c = fgetc(fp)) != EOF){
    for(int i = 0; c != '\n'; i++){
        fscanf(fp, "%c", &c);
        random[i] = c;
    }
}

printf("%s\n", random);

    return 0;
}

标签: c

解决方案


while((c = fgetc(fp)) != EOF){       <-- You consume a byte (H)
    for(int i = 0; c != '\n'; i++){
        fscanf(fp, "%c", &c);        <-- You consume another byte (E) and overwrite c
        random[i] = c;               <-- You read c (H) gets loosed
    }
}

并且您不检查缓冲区溢出,而是

char random[100] = ""; // Initialize, a string must be NUL terminated
int c, i = 0;

while (i < 99 && (c = fgetc(fp)) != EOF && c != '\n')
{
    random[i++] = c;
}

或者更好的是,使用fgets并去除尾随换行符

if (fgets(random, sizeof random, fp))
{
    random[strcspn(random, "\n")] = '\0';
}

编辑:

想象一下文本文件的第一行有一个数字,第二行有一个单词......

在这种情况下,我将使用strtol

int number = 0;
// Line 1 - read the int
if (fgets(random, sizeof random, fp))
{
    int number = (int)strtol(random, NULL, 10); // 10 means base 10 (decimal)

    // As pointed out by @chux in comments, if the line contains 
    // more than 100 chars you end up reading garbage in the next
    // call to fgets, sanitize the line:
    if (strchr(random, '\n') == NULL)
    {
        int c;

        while ((c = fgetc(fp)) != '\n' && c != EOF); // flush garbage
    }
}
// Line 2 - read the string, you can reuse `random`:
if (fgets(random, sizeof random, fp))
{
    random[strcspn(random, "\n")] = '\0';
}
printf("%d %s\n", number, random);

推荐阅读