Hi,

Im having trouble dealing with text files in C. I want to be able to move through the text file which Ive used fseek(). But how do I read one character or read a line of characters from the position I want and change these to float?

Thanks in advance!

Recommended Answers

All 3 Replies

You can read a character at a time.
I personally find this very slow, and since computers these days have lots of memory...

Load the entire file into memory that you allocate with one extra character space, and set it to a '\0' terminator. Then parse the file in memory. VERY fast that way! MAX and NOAA files are some of the biggest I've dealt with and I find this method works best!

HOWEVER, avoid sscanf() or similiar scan type functions. They seem to continue to the end of buffer even after they retrieve a value. I typically have a getword() skipspace() type functions that parse the file, extracting ASCII data objects into working scratch buffers.

A nice way to do this is to put each line of text, into a char buffer[] array, say about 10 char's larger than any line in the text. (roughly).

Then you can use the simpler index of the buffer[] array, to move around as you'd like, and string to float functions are a natural to use, as well.

atof() is one such function, and is defined in stdlib.h (so include that header file). strtof may also be available on your system.

With atof() it works like this:

double myfloat;
char buffer[90] = {"1234.5678"};

myfloat = atoi(buffer);

That's not a complete program, so it won't run. It's there to show the basic skeleton, of using atof(), only.

You can do the same thing by moving around a pointer, inside a file, but it is clumsy, more difficult, and more prone to errors that may destroy the file, or part of the data in the file.

This is the smart way, and the easy way, both.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.