Ayse
Ayse

Reputation: 2754

Read a text file line by line and save each line in the buffer irrespective of data type and length of each line

I want to read one line of the text file, save it to a buffer, send the buffer over a udp socket and then go and read the second line and so on..

So far, since I knew the data type of the text to be read from the text file, I had been using

fscanf()

to read each line from the text file. But now I don't know the data types so it is not possible for me to use this function anymore. Is there any other way to read text file line by line.

Note: The length of each line may vary.

Upvotes: 0

Views: 730

Answers (2)

Abdullah Shoaib
Abdullah Shoaib

Reputation: 2095

Here is a handy code I found to read data as binary

FILE *fp;
fp=fopen("c:\\test.bin", "r");
char *x = new char[10]; 
//size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE      *a_file);
fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

Upvotes: 1

The Marlboro Man
The Marlboro Man

Reputation: 971

Without knowing the data type you can never know what you're going to read into your variables... Let's see, you mention that the length of each line may vary, right?. So we can assume that your text file contains... text. That is, the the number 128 would not be represented by a single integer, but by three chars that you would read and then parse into an integer.

That said, there's not a lot of options there but to build a parser (you read each line and try to guess what it is based on the chars you've read, say, are there only numbers?, are there only numbers but there's a dot? are there only a-z characters?, are they both?) that would't be 100% reliable or just try to always know the data type beforehand (say, save the first char that you read from each line for the data type when writing the file).

A very different story goes on if your text file is not really in text, but in binary mode. If that's the case... well, there's nothing to do but knowing the data types beforehand.

Upvotes: 1

Related Questions