忽略换行符时读取此文件的最佳方法

Best way to read this file while ignoring the new line character

这是我要阅读的文件。

single
splash
single
V-Line
h-line 

用于检查字符串是否相等的宏。

#define STR_MATCH(a,b) (strncmp((a),(b),strlen(b)+1) == 0)

这是我用来阅读的内容。

void readMissilesFile(char* fileName)
{
    FILE* mFile;
    char missile[7];

    /* Open the file. */
    mFile = fopen(fileName, "r");

    if (mFile != NULL)
    {
        while (!feof(mFile))
        {
            fgets(missile, 7, mFile);
            if (!(STR_MATCH(missile, "\n")))
            {
                printf("Missile: %s", missile);
            }
        }
        fclose(mFile);
    }
    else
    {
        perror("Could not open the file.");
    }
}

因此,当我阅读该行时,它会打印出空格,因此我遇到了困难。我试图通过确保它只读取 7 个字符来忽略它,这是每个导弹的最大长度。然后我制作了一个名为 strcmp 的宏,它只检查它们是否相等(希望不打印它)。

请同时找到附件中的宏。

提前致谢,任何帮助都很棒。 :)

stdio.h 中有 getline 函数读取行直到分隔符。不过它是 POSIX,所以如果您在 Windows 上,您可能缺少它。

下面是示例实现: https://github.com/ivanrad/getline/blob/master/getline.c

如果我正确理解你的问题,你可以使用 strcspn.

替换换行符

你不应该这样使用 feofthis post 解释了原因。读取文件直到最后的安全方法是使用 fgets 作为 while 循环中的停止条件。

容器 missile 应该比容纳 '[=16=]'.

的最大字符串的最大大小大 char

Live sample

#include <string.h>
//...
char missile[10];
//...
if (mFile != NULL)
{
    while (fgets(missile, 10, mFile)) //will read till there are no more lines
    {
        missile[strcspn(missile, "\r\n")] = '[=10=]'; //remove newline characters
        printf("Missile: %s ", missile);
    }
}
//...

我建议阅读 this post,其中有关于 fgets 的详细信息,即换行符消耗问题​​。