fgets() 只读取最后一行

fgets() reading only last line

我正在尝试从文本文件中抓取特定行。使用 fgets() 时,它似乎只读取最后一行。我知道 fgets() 覆盖了它读过的前一行,但它似乎在最后一行 starting 然后结束。

我正在尝试读取的文件:

PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

我正在尝试获取第二行:NAME="Debian GNU/Linux"

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUFFER_SIZE 1024

int main(void)
{
    char buf[BUFFER_SIZE];
    buf[strlen(buf) - 1] = 0;

    // this line stores the command output into release.txt
    system("cat /etc/os-release >> release.txt");
    const char* fileName = "./release.txt";
    fp = fopen(fileName, "r");
    if (fp == NULL)
    {
        printf("Couldnt not open file %s\n", fileName);
    }

    char ostype;
    int index = 0;
    while (fgets(buf, BUFFER_SIZE, fp) != NULL);
    {
        s = strstr(buf, "NAME");
        if (s != NULL)
        {
            printf("ostype: %s\n", s);  
        }
        else
        {
            printf("not found\n");  
            printf("buffer %s\n", buf2);
        }
        index++; //index is to confirm it's only reading the last line
    }

    fclose(fp);
    
    printf("Loop ran %d times.\n", index);

    return 0;   
}

我的输出如下:

not found
buffer BUG_REPORT_URL="https://bugs.debian.org/"


Loop ran 1 times.

我在我的代码中的其他地方使用了与另一个文件相同的逻辑,它完全按预期工作。

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUFFER_SIZE 1024

int main(void)
{
    char buf[BUFFER_SIZE];

    buf[strlen(buf) - 1] = 0;
    system("cat /proc/cpuinfo >> cpuinfo.txt");

    // Read file
    FILE *fp;
    const char* fileName1 = "./cpuinfo.txt";

    fp = fopen(fileName1, "r");
    if (fp == NULL)
    {
        printf("Could not open file %s", fileName1);
        return 1;
    }

    char *s;
    int numProcessors;
    int numCores;
    while (fgets(buf, BUFFER_SIZE, fp) != NULL)
    {
        // find number of processors
        s = strstr(buf, "processor");
        if (s != NULL)
        {
            //printf("*** %s\n", &s[11]);
            numProcessors = atoi(&s[11]);
        }

        // find number of physical cores
        s = strstr(buf, "physical id");
        if (s != NULL)
        {
            numCores = atoi(&s[13]);
        }


    }
    system(">cpuinfo.txt");
    fclose(fp)

    return 0;
}

您似乎在 while 循环行上插入了一个额外的 semi-colon:

while (fgets(buf, BUFFER_SIZE, fp) != NULL);

这会导致循环只读取每一行而不对其进行任何操作。您打算成为循环一部分的大括号内的代码仅在循环完成后运行,从而处理文件最后一行 buf 中剩余的内容。