Replacing strings in files - C - c

I'm trying to make a program that replacing strings in files.
I got the program below that replacing all the occurrences of one string in the file, but now I need to extend so it'll replace multiple strings.
The trivial way is to run the program several times, each time with different string as input, but I'm looking for more efficient way to do it.
My input can be:
Set of strings to replace (each string appears once).
List of strings to replace by order of appearance (string can be at the list several times) but without knowing their offset.
Thanks for the help.
#include <stdio.h>
#include <string.h>
#define LINE_LEN 128
int main(){
char fileOrig[32] = "orig.txt";
char fileRepl[32] = "new.txt";
char text2find[80];
char text2repl[80];
printf("enter text to replace in the file:");
scanf ("%s",text2find);
sprintf(text2repl,"%s%s%s","<b><font color=\"#FF0000\">",text2find,"</font></b>");
char buffer[LINE_LEN+2];
char *buff_ptr, *find_ptr;
FILE *fp1, *fp2;
int buff_int;
size_t find_len = strlen(text2find);
fp1 = fopen(fileOrig,"r");
fp2 = fopen(fileRepl,"w");
buff_int=(int)buffer;
while(fgets(buffer,LINE_LEN+2,fp1)){
buff_ptr = buffer;
while ((find_ptr = strstr(buff_ptr,text2find))){
while(buff_ptr < find_ptr)
fputc((int)*buff_ptr++,fp2);
fputs(text2repl,fp2);
buff_ptr += find_len;
}
fputs(buff_ptr,fp2);
}
fclose(fp2);
fclose(fp1);
return 0;
}

Sometimes things can get complicated. Say if you have strings to replace as {ab,ba} and they would be replaced to {xy,yx} respectively. Say you have the input file to contain "aba". Now the output becomes order dependant.
Similar confusion can occur if the replacement of one string causes another string to be formed which belongs to the strings-to-replace list.
IMO, you should define what you want to do in this situations and then use an approach similar to what you have already done.
BTW, you can better your string matching by using an finite automata based approach or use some existing state of the art algorithm like KMP or Boyer-Moore. This will let you search multiple strings at once.

I'm not sure if what you want is possible, but you might want to look into string search algorithms to make the search part of your algorithm more optimized. A naive search algorithm has, according to Wikipedia, complexity Θ((n-m+1) m), with n the length of your text and m the length of your search string. Take a look at the link, you can do significantly better.
Once you have all the offsets of the strings to replace, the actual replacing seems to be fairly straightforward.
I'm sorry I can't completely answer your question, but I thought this might give you some optimization ideas.

I think this will help you. Please use following Code to Search & Replace string .
Call this function from Top lavel function like this:
replaceIPAddress( "System.cfg", "172.16.116.157", "127.0.0.1");
void replaceIPAddress( char * confFileName, char *text_to_find , char *text_to_replace )
{
FILE *input = fopen(confFileName, "r");
FILE *output = fopen("temp.txt", "w");
char buffer[512];
while (fgets(buffer, sizeof(buffer), input) != NULL)
{
char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
/* Allocate memory for temporary buffer */
char *temp = calloc(
strlen(buffer) - strlen(text_to_find) + strlen(text_to_replace) + 1, 1);
/* Copy the text before the text to replace */
memcpy(temp, buffer, pos - buffer);
/* Copy in the replacement text */
memcpy(temp + (pos - buffer), text_to_replace, strlen(text_to_replace));
/* Copy the remaining text from after the replace text */
memcpy(temp + (pos - buffer) + strlen(text_to_replace),
pos + strlen(text_to_find),
1 + strlen(buffer) - ((pos - buffer) + strlen(text_to_find)));
fputs(temp, output);
free(temp);
}
else
fputs(buffer, output);
}
fclose(output);
fclose(input);
/* Rename the temporary file to the original file */
rename("temp.txt", confFileName);
}

//
// Find and replace data in a file
//
// This is not as straightforward a problem as it initially appears,
// because if you have the text
//
// "Jack is a pirate"
//
// And you wish to replace "is" with "was", the string needs to be longer,
// or else you end up with the following:
//
// "Jack wasapirate"
//
// This becomes more of a problem for larger text. For example, if we wanted
// to replace "Jack" with "Rumpelstiltskin", we'd end up with:
//
// "Rumpelstiltskin"
//
// Which completely overwrites our original text!!!
//
// In order to do this correctly, we wither need to:
//
// 1. Read the entire file into a in-memory buffer
// 2. Write to a temporary file, then replace the original file
//
// Option #2 is easier to implement, and should work for your coursework.
//
#include <stdio.h>
int main(int argc, char** argv)
{
// We need a buffer to read in data
const int BufferSize = 0x1000;
char Buffer[BufferSize];
char *InputFileName = "input.txt";
char *TemporaryFileName = "temp.txt";
// Open the file for reading. 'rt' means that it must already exist, for reading.
FILE *Input = fopen(InputFileName, "rt");
// Our output file. 'w+' means to create the file if it doesnt exist, for writing.
FILE *Output = fopen(TemporaryFileName, "w+");
// Our find and replace arguments
char *Find = "is";
char *Replace = "was";
if(NULL == Input)
{
printf("Could not open file");
return 1;
}
printf("Find: %s\n", Find);
printf("Replace: %s\n", Replace);
// For each line...
while(NULL != fgets(Buffer, BufferSize, Input))
{
// For each incidence of "is"
char *Stop = NULL; // Where to stop copying (at 'is')
char *Start = Buffer; // Start at the beginning of the line, and after each match
printf("Line: %s\n", Buffer);
while(1)
{
// Find next match
Stop = strstr(Start, Find);
if(NULL == Stop)
{
// Print the remaining text in the line
fwrite(Start, 1, strlen(Start), Output);
break;
}
// Write out everything between the end of the previous match, and the
// beginning of the current match.
//
// For example:
//
// "Jack is a pirate who is cool"
//
// Has two instances to replace. In order, we'd find them as such:
//
// "Jack is a pirate who is cool"
// ^
// ^
// What we want to do is write:
// - "Jack "
// - "was"
// - "a pirate who "
// - "was"
// - "cool"
printf("Match starts at: %s\n", Stop);
// We have found a match! Copy everything from [Start, Stop)
fwrite(Start, 1, Stop - Start, Output);
// Write our replacement text
fwrite(Replace, 1, strlen(Replace), Output);
// Next time, we want to start searching after our 'match'
Start = Stop + strlen(Find);
printf("Search resumes at: %s\n", Start);
};
}
// Close our files
fclose(Input);
fclose(Output);
// If desired, rename the Output file to the Input file
rename(TemporaryFileName, InputFileName);
return 0;
}

Related

Edit txt file using library from C

I am facing problems scanning an existing file.
The challenge is that I have a source text file with some strings. I have to scan this file for the word "o'clock", and where I find it, I have to take the word before "o'clock" and enclose it in square brackets.
I found a function to find the trigger, but I don't understand what I need to do next. I would be grateful if you could explain how to replace the characters in the read string.
For example: We have a string:
"Let's go to the graveyard at night - at twelve o'clock!"
I need to replace the word twelve with [twelve].
Here is the code:
#include <stdio.h>
#include <string.h>
int main() {
FILE * fp; //open exists file
FILE * fn; //open empty file
char c[1000]; // buffer
char trigger[] = "o'clock"; // the word before which the characters should be added
char name [] = "startFile.txt"; // name of source file
char secondName[] = "newFile.txt"; // name of output file
fp = fopen (name, "r"); // open only for reading
if (fp == NULL) { // testing on exists
printf ( "Error");
getchar ();
return 0;
}
fn = fopen(secondName, "w"); // open empty file for writing
while (!feof(fp)) { // scanning all string in the source
if(fgets(c,1000, fp) != NULL) { // reading charter from file
fprintf(fn, c); // writing charter from buffer "c" to empty file
if (strstr(c, trigger)) { // find triggered word
// I tried compare string which has a trigger-word
}
}
}
fclose(fp); // closing file
fclose(fn);
return 0;
}
In your code, you copy the line to the output file and then, afterwards, look for the trigger word. But the goal is to find the trigger and edit the string, and only then write the line to the output file. Also, in order to edit the line, you need to know where the trigger was found so you need to save the output of the search.
So, instead of:
fprintf(fn, c); // writing charter from buffer "c" to empty file
if (strstr(c, trigger)) { // find triggered word
// I tried compare string which has a trigger-word
}
We need:
char *p = strstr(c, trigger);
if (p) {
// I tried compare string which has a trigger-word
}
fputs(c, fn); // writing charter from buffer "c" to empty file
So now we found the trigger and we need to search backwards to find the end and then the start of the word before it. When we find them we need to create a spot and insert the edits:
char *p = strstr(c, trigger);
if (p) {
// ok we found the trigger - now we need to search backwards
// to find the end and then the start of the word before
while (p>c && p[-1]==' ') p--; // find the end of the word
memmove(p+1, p, c+999 - p); // make a space for the ]
*p = ']';
while (p>c && p[-1]!=' ') p--; // find the start of the word
memmove(p+1, p, c+999 - p); // make a space for the [
*p = '[';
}
fputs(c, fn); // writing charter from buffer "c" to empty file
Try it here: https://www.onlinegdb.com/H18Tgy9xu
But then, what if there was more than one "o-clock" in the string? Something like this:
Let's go to the graveyard at twelve o'clock and have dinner at six o'clock beforehand!
In that case, you need to loop around until you have found all of them:
Here is the final code:
#include <stdio.h>
#include <string.h>
int main() {
FILE * fp; //open exists file
FILE * fn; //open empty file
char c[1000]; // buffer
char trigger[] = "o'clock"; // the word before which the characters should be added
char name [] = "startFile.txt"; // name of source file
char secondName[] = "newFile.txt"; // name of output file
fp = fopen (name, "r"); // open only for reading
if (fp == NULL) { // testing on exists
printf ( "Error");
getchar ();
return 0;
}
fn = fopen(secondName, "w"); // open empty file for writing
if (fn == NULL) { // testing on create
printf ( "Error");
getchar ();
return 0;
}
while (fgets(c, 1000, fp)) { // scanning all string in the source
char *p = c; // we need to start searching at the beginning
do {
p = strstr(p+1, trigger); // find the next oclock after this one
if (p) {
// ok we found the trigger - now we need to search backwards
// to find the end and then the start of the word before
while (p>c && p[-1]==' ') p--; // find the end of the word
memmove(p+1, p, c+999 - p); // make a space for the ]
*p = ']';
while (p>c && p[-1]!=' ') p--; // find the start of the word
memmove(p+1, p, c+999 - p); // make a space for the [
*p = '[';
p = strstr(p, trigger); // find that same oclock again
// (we couldn't save the location because memmove has changed where it is)
}
} while (p); // as long as we found one, search again
fputs(c, fn); // writing charter from buffer "c" to empty file
}
fclose(fp); // closing file
fclose(fn);
return 0;
}
Try it here: https://onlinegdb.com/SJMrP15ld

How to edit specific parts of a file based on user input in C?

I am doing a homework assignment that requires me to create a program for making a dictionary. Most of my assignment is done, but I am stuck on the most complicated part. The part of the assignment I'm stuck on reads:
Editing a Dictionary (E)
Insert a new word (I) (15 points)
If the word is available, it should alert a message.
Otherwise, insert the new word
Delete a word (D) (15 points)
If the word is not available, it should alert a message.
Otherwise, delete the word
Editing a word (U) (10 points)
If the word is not available, it should alert a message
Currently the file I am working with looks like this:
Name of product: Dictionary
Description: Spanish to English Dictionary
Developer: Robert
Date of Creation: 12/02/2017
Number of words: 0
***************************************************************************
1. Red Rojo
2. Cat Gato
3. Apple Manzana
4. Love Amor
5. Car Carro
and I am wondering how I can read, and do the operations above. Most of the stuff on google is very complicated for my current skillset. Here is what I have so far? Can someone ELI5 the general process of what I should be doing in this case? Should I be using structs? How can I interact with the file in the way my professor wants me to? Here is my basic code I have for this section so far:
int editDictionary(char *oDict) {
char array[1000];
char temp[100];
FILE * dictPtr; // dictPtr = dictionary.dic file pointer
/* fix directory for dictionaries */
strcat(temp,"./dicts/");
strcat(temp,oDict);
strcpy(oDict,temp);
/* open dictPtr file for rw */
dictPtr = fopen (oDict,"a+");
fscanf(dictPtr,"%s",array[1]);
/* text scan values */
for(int i = 0; i <5; i ++) printf("%s", array[i]);
return 1;
}
Your task is pretty tedious and requires knowledge of some inbuilt functions in C.
Since, this is your homework assignment, providing the entire code to you would do no good in improving your current skillset. So, I will provide the code for performing the delete operation the dictionary which is the trickiest of all. Rest you have to figure out yourself. The code in delete_dict is more than enough to help you write other functions.
I've added the explanations in the code for most of the functions used but you should still look up their documentation to understand what each function does.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *WORD_COUNT_LABEL = "Number of words: ";
void delete_word(const char *filename, const char *word)
{
//add alerts
char read[100];
FILE *f = fopen(filename, "r");
int exists = 0; //the count of words that exist
//check if word exists
//fgets is used to read a line into the buffer/temp memory read
while (fgets(read, 100, f))
{
//strstr - finds substring
if (strstr(read, word))
{
exists++;
}
}
if (exists == 0)
{
fclose(f);
return;
}
//The main objective to read the file two times is
//because we want to edit the NUMBER_OF_WORDS in the file as well
//now we know that a word exists
//so move flie pointer to beginning
fseek(f, 0, SEEK_SET);
FILE *nf = fopen("dict_t.txt", "w");
int count;
char num[10];
char *p;
while (fgets(read, 100, f))
{
//if word count label is found update it
//return the pointer to the location of match
if (p = strstr(read, WORD_COUNT_LABEL))
{
p += strlen(WORD_COUNT_LABEL);
//incrementing the pointer to the position where number is to be updated
count = atoi(p); //converts integer from char * to int
count -= exists;
sprintf(num, "%d", count); //converts interger from int to char *
strcpy(p, num); //copy new number at that location
strcat(p, "\n");
}
else if (p = strstr(read, word))
{
//if we find the word to be deleted
//we set the first character in read as NULL
//so that nothing is written onto the new file.
read[0] = '\0';
}
//writes char * to file
fputs(read, nf);
}
//rest is self explanatory
fclose(nf);
fclose(f);
remove(filename);
rename("dict_t.txt", filename);
}

Reading content from multiple files in C

Example:
Three files
hi.txt
Inside of txt: "May we be"
again.txt
Inside of txt: "The ones who once"
final.txt
Inside of txt: "knew C"
And then, another file called "order"
order.txt
Inside of txt:
"hi.txt;6"
"again.txt;7"
"final.txt;3"
What I want: read the first file name, open it, list the content, wait 6 seconds, read the second name, open it, list the content, wait 7 seconds, read the third name, open it, list the content, wait 3 seconds.
If I do it without opening the content (you'll see a second while on my code) and list the names, it works, yet for some reason it doesn't when it's about the content.
orderFile = fopen("order.txt","r");
while(fscanf(orderFile,"%49[^;];%d",fileName,&seconds) == 2)
{
contentFile = fopen(fileName,"r");
while(fscanf(contentFile,"%[^\t]",textContent) == 1)
{
printf("%s\n", textContent);
}
sleep(seconds);
fclose(contentFile);
}
fclose(orderFile);
Output:
May we be
(Waits 7 seconds)
Program closes with "RUN SUCCESSFUL"
EDIT#
It works now, as you guys said, this was the problem:
Old:
while(fscanf(orderFile,"%49[^;];%d",fileName,&seconds) == 2)
New:
while(fscanf(orderFile," %49[^;];%d",fileName,&seconds) == 2)
I'm having a "hard" time to completely understand it, what does the space does? doesn't accept enters? spaces? What exactly is it?
Don't use fscanf for that
int
main()
{
FILE *orderFile = fopen("order.txt", "r");
if (orderFile != NULL)
{
int seconds;
char line[128];
/*
* fgets, read sizeof line characters or unitl '\n' is encountered
* this will read one line if it has less than sizeof line characters
*/
while (fgets(line, sizeof line, orderFile) != NULL)
{
/*
* size_t is usually unsigned long int, and is a type used
* by some standard functions.
*/
size_t fileSize;
char *fileContent;
FILE *contentFile;
char fileName[50];
/* parse the readline with scanf, extract fileName and seconds */
if (sscanf(line, "%49[^;];%d", fileName, &seconds) != 2)
continue;
/* try opening the file */
contentFile = fopen(fileName,"r");
if (contentFile == NULL)
continue;
/* seek to the end of the file */
fseek(contentFile, 0, SEEK_END);
/*
* get current position in the stream,
* it's the file size, since we are at the end of it
*/
fileSize = ftell(contentFile);
/* seek back to the begining of the stream */
rewind(contentFile);
/*
* request space in memory to store the file's content
* if the file turns out to be too large, this call will
* fail, and you will need a different approach.
*
* Like reading smaller portions of the file in a loop.
*/
fileContent = malloc(1 + fileSize);
/* check if the system gave us space */
if (fileContent != NULL)
{
size_t readSize;
/* read the whole content from the file */
readSize = fread(fileContent, 1, fileSize, contentFile);
/* add a null terminator to the string */
fileContent[readSize] = '\0';
/* show the contents */
printf("%s\n", fileContent);
/* release the memory back to the system */
free(fileContent);
}
sleep(seconds);
fclose(contentFile);
}
fclose(orderFile);
}
return 0;
}
Everything is barely explained in the code, read the manuals if you need more information.

Read comma-separated "quoted" strings from a file

I am new to C programming but have a bit of Java knowledge, so I want to write a program that reads strings stored in a file, possibly several names separated by comma, such as "boy","girl","car" etc. In Java I would use something like, string str[]=str1.split(" ");.
So I came up with several codes each time but none seems to work, here is my most recent code:
fscanf(fp,"%[^\n]",c);
But this essentially prints the whole line till a new line is found. I have also tried using
fscanf(fp,"%[^,]",c);
And if I use gets() it only gets the first string and ignores all others from the first comma.
This didn't give any reasonable output, it rather gave some minute(encoded) characters.
Please can anyone help me with how to pick out string values separated by comma and in quotes
You can use strtok() function (string.h) to do this task. store the file data in a string of a considerable size. and apply
str = strtok(full_file_string,",");
/* you can save this string in a 2 dimensional array of characters or print it */
while(NULL != str)
{
str=strtok(NULL,",");
/*print or save your next word here as you like */
}
for further reference see manpage of strtok.
Hope this might help you :)
fscanf doesn't work with regular expressions, but rather with placeholders. So you need to specify the placeholder for what you want to read, and then fscanf will get the next element that matches your pattern. To get what you want one would use something like:
char word[enough_space];
.
.
.
while(fscanf(fp, "\"%s\"", word) != EOF)
{
//Do something with yout word.
};
Here you will be trying to get a string between to quotes. Note how the placeholder indicates which part of the match should be saved. on successive calls fscanf will get to the next match and so on. When it consumes the whole file it will return EOF.
Below example will extract the substring. The format of your fille should be something like:
"boy","girl","car",
Notice that file string should end with ','
int read_file_with_string_tokens() {
char * tocken;
char astring[127];
int current = 0;
int limit;
char *filebuffer = NULL;
FILE *file = fopen("your/file/path/and/name", "r");
if (file != NULL) {
fseek(file, 0L, SEEK_END);
int f_size = ftell(file);
fseek(file, 0L, SEEK_SET);
filebuffer = (char*) malloc(f_size + 2);
if (filebuffer == NULL) {
pclose(file);
free(filebuffer);
return -1;
}
memset(filebuffer, 0, f_size + 2);
if (fgets(filebuffer, f_size + 1, file) == NULL) {
fclose(file);
free(filebuffer);
return -1;
}
fclose(file);
memset(astring, 0, 127);
char *result = NULL;
tocken = strchr(filebuffer, ',');
while (tocken != NULL) {
limit = tocken - filebuffer + 1;
strncpy(astring, &filebuffer[current], limit - current - 1);
printf("%s" , astring);
current = limit;
tocken = strchr(&filebuffer[limit], ',');
memset(astring, 0, 127);
}
free(filebuffer);
}
return 0;
}
#include <stdio.h>
int main(void){
char line[128];
char word[32];
FILE *in, *out;
int line_length;
in = fopen("in.txt", "r");
out = fopen("out.txt", "w");
while(1==fscanf(in, "%[^\n]%n\n", line, &line_length)){//read one line
int pos, len;
for(pos=0;pos < line_length-1 && 1==sscanf(line + pos, "%[^,]%*[,]%n", word, &len);pos+=len){
fprintf(out, "%s\n", word);
}
}
fclose(out);
fclose(in);
return 0;
}
/* output result out.txt
"boy"
"girl"
"car"
...
*/

Reading text file into an array of lines in C

Using C I would like to read in the contents of a text file in such a way as to have when all is said and done an array of strings with the nth string representing the nth line of the text file. The lines of the file can be arbitrarily long.
What's an elegant way of accomplishing this? I know of some neat tricks to read a text file directly into a single appropriately sized buffer, but breaking it down into lines makes it trickier (at least as far as I can tell).
Thanks very much!
Breaking it down into lines means parsing the text and replacing all the EOL (by EOL I mean \n and \r) characters with 0.
In this way you can actually reuse your buffer and store just the beginning of each line into a separate char * array (all by doing only 2 passes).
In this way you could do one read for the whole file size+2 parses which probably would improve performance.
It's possible to read the number of lines in the file (loop fgets), then create a 2-dimensional array with the first dimension being the number of lines+1. Then, just re-read the file into the array.
You'll need to define the length of the elements, though. Or, do a count for the longest line size.
Example code:
inFile = fopen(FILENAME, "r");
lineCount = 0;
while(inputError != EOF) {
inputError = fscanf(inFile, "%s\n", word);
lineCount++;
}
fclose(inFile);
// Above iterates lineCount++ after the EOF to allow for an array
// that matches the line numbers
char names[lineCount][MAX_LINE];
fopen(FILENAME, "r");
for(i = 1; i < lineCount; i++)
fscanf(inFile, "%s", names[i]);
fclose(inFile);
For C (as opposed to C++), you'd probably wind up using fgets(). However, you might run into issues due to your arbitrary length lines.
Perhaps a Linked List would be the best way to do this?
The compiler won't like having an array with no idea how big to make it. With a Linked List you can have a really large text file, and not worry about allocating enough memory to the array.
Unfortunately, I haven't learned how to do linked lists, but maybe somebody else could help you.
If you have a good way to read the whole file into memory, you are almost there. After you've done that you could scan the file twice. Once to count the lines, and once to set the line pointers and replace '\n' and (and maybe '\r' if the file is read in Windows binary mode) with '\0'. In between scans allocate an array of pointers, now that you know how many you need.
you can use this way
#include <stdlib.h> /* exit, malloc, realloc, free */
#include <stdio.h> /* fopen, fgetc, fputs, fwrite */
struct line_reader {
/* All members are private. */
FILE *f;
char *buf;
size_t siz;
};
/*
* Initializes a line reader _lr_ for the stream _f_.
*/
void
lr_init(struct line_reader *lr, FILE *f)
{
lr->f = f;
lr->buf = NULL;
lr->siz = 0;
}
/*
* Reads the next line. If successful, returns a pointer to the line,
* and sets *len to the number of characters, at least 1. The result is
* _not_ a C string; it has no terminating '\0'. The returned pointer
* remains valid until the next call to next_line() or lr_free() with
* the same _lr_.
*
* next_line() returns NULL at end of file, or if there is an error (on
* the stream, or with memory allocation).
*/
char *
next_line(struct line_reader *lr, size_t *len)
{
size_t newsiz;
int c;
char *newbuf;
*len = 0; /* Start with empty line. */
for (;;) {
c = fgetc(lr->f); /* Read next character. */
if (ferror(lr->f))
return NULL;
if (c == EOF) {
/*
* End of file is also end of last line,
` * unless this last line would be empty.
*/
if (*len == 0)
return NULL;
else
return lr->buf;
} else {
/* Append c to the buffer. */
if (*len == lr->siz) {
/* Need a bigger buffer! */
newsiz = lr->siz + 4096;
newbuf = realloc(lr->buf, newsiz);
if (newbuf == NULL)
return NULL;
lr->buf = newbuf;
lr->siz = newsiz;
}
lr->buf[(*len)++] = c;
/* '\n' is end of line. */
if (c == '\n')
return lr->buf;
}
}
}
/*
* Frees internal memory used by _lr_.
*/
void
lr_free(struct line_reader *lr)
{
free(lr->buf);
lr->buf = NULL;
lr->siz = 0;
}
/*
* Read a file line by line.
* http://rosettacode.org/wiki/Read_a_file_line_by_line
*/
int
main()
{
struct line_reader lr;
FILE *f;
size_t len;
char *line;
f = fopen("foobar.txt", "r");
if (f == NULL) {
perror("foobar.txt");
exit(1);
}
/*
* This loop reads each line.
* Remember that line is not a C string.
* There is no terminating '\0'.
*/
lr_init(&lr, f);
while (line = next_line(&lr, &len)) {
/*
* Do something with line.
*/
fputs("LINE: ", stdout);
fwrite(line, len, 1, stdout);
}
if (!feof(f)) {
perror("next_line");
exit(1);
}
lr_free(&lr);
return 0;
}

Resources