#fgets() or any other function for reading txt files

26 messages · Page 1 of 1 (latest)

limber leaf
#

I want to read a text file from my C lang code.

But im not sure should i use fgets or any other function.
becuase in fgets() we have one paramater that store the number of maximum number of characters to be read.

But how would i know how many number of characters i want to read? if files are random or something else

tepid sparrowBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

night veldt
#

fgets() will read one line at a time, or the whole of the buffer. Or until you reach EOF. Whichever happens first.
So if your buffer is sufficiently large to hold the longest line in the file, then you needn't worry.

#

Obviously, you will need to call fgets() until you reach EOF.

limber leaf
#

or n parameter is optional??

stuck valley
#

no, you can just pass it the size of the buffer you're reading into though

night veldt
#
#define BUFFER_SIZE 256
char buffer[BUFFER_SIZE] = {0};

while (fgets(buffer, BUFFER_SIZE, file) != NULL) {
  // process data
}

Something like this, ig.

limber leaf
#

okk got it

#

but if i use Dynamic allocation for the buffer?

night veldt
#

Why?

stuck valley
#

if you do: pass it the size of the dynamically allocated buffer

night veldt
#

Have you got ESP built in?

limber leaf
limber leaf
night veldt
#

Extrasensory perception.
A.k.a. foresight.

#

How would you know how long the next line is before you even read it?

limber leaf
#

so i can use python to find the maximum line then pass that variable

night veldt
#

Okay, you could fgetc() and ungetc() to read ahead and find the next newline.
But really?

limber leaf
#

im just wondring if i use dynamic allocation then it is posible to read with fgets

night veldt
#

Yes, but you are making life REALLY hard for yourself.

limber leaf
#

nah nah im just thinking about that :_) what will happen if i dont know the size of maximum line

#

!solved