osolmaz
osolmaz

Reputation: 1923

Splitting ASCII text files in C

Suppose I have the following code in C:

FILE* a=fopen("myfile.txt","r");
FILE* b,c;

There is a delimiter line in 'a', which designates the place where I want to split; and I want to split the contents of 'a' into 'b',and 'c'. I want to do this without creating any other files.

Also later, I want to do this dynamically, by creating a pointer array pointing to 'FILE*'s. So the number of delimiter lines will be arbitrary.

For this case, suppose that the delimiter line is any line that has the string 'delim'.

Upvotes: 1

Views: 282

Answers (1)

idefixs
idefixs

Reputation: 712

The concept could be:

1) fopen() INFILE and (first) OUTFILE

2) while you can, fgets() lines from INFILE and strncmp() them to the delimiter

2.a) delimiter not found: fputs() the line to OUTFILE

2.b) delimiter found: fclose() OUTFILE and fopen() the next OUTFILE

2.c) end of file: break loop

3) fclose() INFILE and OUTFILE

Or this way:

1) fopen()INFILE

2) fseek() to the end of the stream and use ftell() to get the file position, let's call this N

3) rewind() the stream and fread() N bytes from it into a buffer.

4) fclose()INFILE

5) while you can, strstr() the delimiter in your buffer and fwrite() the data blocks inbetween to OUTFILEs

Upvotes: 2

Related Questions