okami
okami

Reputation: 2153

C file read by line up to a custom delimiter

Is there a function in C to read a file with a custom delimiter like '\n'?

For example: I have:

I did write \n to exemplify in the file is the LF (Line feed, '\n', 0x0A)

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

I'd like the file to read by part and split it in two strings:

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

I know fgets I can read up to a num of characters but not by any pattern. In C++ I know there is a method but in C how to do it?

I'll show another example:

I'm reading a file ABC.txt

abc\n
def\n
ghi\n

With the following code:

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);

I excpected fgets had to stop on abc\n

But the res is filled with: abc\ndef\nghi\n

SOLVED: The problem is that I was using Notepad++ in WindowsXP (the one I used I don't know it happens on other windows) saved the file with different encoding.

The newline on fgets needs the CRLF not just the CR when you type enter in notepad++

I opened the windows notepad And it worked the fgets reads the string up to abc\n on the second example.

Upvotes: 0

Views: 7071

Answers (1)

Kamal
Kamal

Reputation: 7800

fgets() will read one line at a time, and does include the newline character in the line output buffer. Here's an example of the common usage.

#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;
}

But since you asked about using a "custom" delimiter... getdelim() allows you to specify a different end-of-line delimiter.

Upvotes: 1

Related Questions