0

C 中是否有一个函数可以读取带有“\n”之类的自定义分隔符的文件?

例如:我有:

我确实写了\n来举例说明文件是LF(换行,'\n',0x0A)

this is the firstline\n this is the second line\n

我希望文件按部分读取并将其拆分为两个字符串:

this is the firstline\n
this is the second line\n

我知道 fgets 我最多可以读取多个字符,但不能读取任何模式。在 C++ 中我知道有一种方法,但在 C 中怎么做呢?

我将展示另一个示例:

我正在阅读一个文件 ABC.txt

abc\n
def\n
ghi\n

使用以下代码:

FILE* fp = fopen("ABC.txt", "rt");
const int lineSz = 300;
char line[lineSz];
char* res = fgets(line, lineSz, fp); // the res is filled with abc\ndef\nghi\n
fclose(fp);

我预计 fgets 必须在 abc 上停止\n

但是 res 里面填的是:abc\ndef\nghi\n

已解决:问题是我在 WindowsXP 中使用 Notepad++(我使用的那个我不知道它会发生在其他 Windows 上)用不同的编码保存了文件。

当您在 notepad++ 中输入时,fgets 上的换行符不仅需要 CR,还需要 CRLF

我打开了 Windows 记事本,它在第二个示例中 fgets 将字符串读取到 abc\n 。

4

1 回答 1

1

fgets()将一次读取一行,并且在行输出缓冲区中包含换行符。这是常见用法的示例。

#include <stdio.h>
#include <string.h>
int main()
{
    char buf[1024];
    while ( fgets(buf,1024,stdin) )
        printf("read a line %lu characters long:\n  %s", strlen(buf), buf);
    return 0;
}

但是由于您询问使用“自定义”分隔符...getdelim()允许您指定不同的行尾分隔符。

于 2010-11-16T00:52:37.547 回答