C using fread to read an unknown amount of data

I have a text file test.txt

There will be a number inside, it can be as follows:

1 2391 32131231 3123121412 

I. It can be any size of a number, from 1 digit to x digits.

There will be only 1 thing in the file - this is a number. I want some code using fread that will read this number of bytes from a file and put it in a variable of the appropriate size.

Can anyone suggest a better way to solve this problem?

+4
source share
4 answers

You can simply use:

 char buffer[4096]; size_t nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp); if (nbytes == 0) ...EOF or other error... else ...process nbytes of data... 

Or, in other words, provide yourself with a data space large enough for any valid data, and then write down how much data was actually read in the line. Note that a line will not have a null end, unless buffer contained all zeros before fread() or the file contained null bytes. You cannot rely on a local variable to be nullified before use.

It is unclear how you want to create a “corresponding size variable”. You can use dynamic memory allocation ( malloc() ) to provide the correct amount of space, and then return the selected item from this function. Remember to check for zero return (from memory) before using it.

+4
source

One way to achieve this is to use fseek to move the file location of the file to the end of the file:

 fseek(file, SEEK_END, SEEK_SET); 

and then using ftell to get the cursor position in the file - this returns the position in bytes so that you can then use this value to allocate a large enough buffer and then read the file into this buffer.

I saw warnings that say that this may not always be 100% accurate, but I used it in several cases without problems - I think that problems may depend on specific implementations of functions on certain platforms.

+1
source

If you want to avoid over reading, fread not a valid function. You probably want fscanf with the conversion pointer to the lines %100[0123456789] ...

+1
source

Depending on how smart you are with number conversion ... Unless you need to be particularly smart and fast, you can read its character in a type with getc . So, start with the variable initialized to 0. Read the character, multiply the variable by 10 and add a new digit. Then repeat to the end. Get a larger variable as needed along the way, or start with the largest variable of size, and then copy it to the smallest size that fits after you finish.

0
source

Source: https://habr.com/ru/post/1385710/


All Articles