reading file contents in C, keeping track of new lines - c

I am reading strings in from a data file in C using fscanf() using a loop that goes until EOF. The data file contains strings separated by any white space. As the strings are read in with fscanf() they will be checked for any invalid information. I need to keep track of the line numbers that an item is on so that if an invalid item is detected the line number of that item will be displayed. Like I said though, the data file is not just one string per line. Is there anything more elegant than reading in everything up to a new line, splitting that into individual strings, and checking those strings? Can I determine the line number where the file pointer is currently pointing?

There is no line number counter in the C I/O libraries. You need to keep track of the line number yourself.
I suggest that you read one line at a time using fgets, incrementing your line number counter each time, and then read items from that string using sscanf.

Related

How to move back to the starting of previous line after reading a line using fgets()?

For example if the file contains:
12345
-3445654
1245646
I want to read the first line into a string using fgets(). Then I want to read the second line in too check if there is a '-' in the first spot. If there is one, I will read the second line and strcat it to the first line.
Then I want to read the thrid line using fgets() again. This time when there is no '-' I just want to make the file go back to the beginning of the third line so that the next time I call fgets() it will read the same third line again.
Is there a way I can do this?
Use fgetc to read the first character on the next line, and if it's not a '-' use ungetc to put it back.
Generally you would just keep the part of the file just read, in the memory until you are sure you don't need it anymore.
Or you could read the entire file into a buffer and then jump around it using pointer as much as you like.
Or if you really must, you can more the current stream position with fseek, and then re-read the parts you need.
Whenever I want to
read a line
read a second line
maybe do something involving both the first line and the second line
what I usually do is declare a second line-holding variable
char prevline[whateversize];
and then, somewhere between step 1 and step 2
strcpy(prevline, line);
(Naturally you have to be sure that the line and prevline variables are consistently allocated, e.g. as arrays of the same size, so that overflow isn't a problem.)

how to read last n lines from a file in C

Its a microsoft interview question.
Read last n lines of file using C (precisely)
Well there could be so many ways to achieve this , few of them could be :
-> Simplest of all, in first pass , count the number of lines in the file and in second pass display the last n lines.
-> Or may be maintain a doubly linked-list for every line and display the last n lines by back traversing the linkedlist till nth last node.
-> Implement something of sort tail -n fname
-> In order to optimize it more we can have double pointer with length as n and every line stored dynamically in a round robin fashion till we reach the end of file.
for example if there are 10 lines in file and want to read last 3 lines. then we could create a array of buffer as buf[3][] and at run time would keep on mallocing and freeing the buffer in circular way till we reach the last line and keep a counter to know the current index of array.
Can anyone please help me with more optimized solution or atleast guide me if any of the above approaches can help me get the correct answer or any other popular approach/method for such kind of questions.
You can use a queue and to store the last n lines seen in this queue. When you see the eof just print the queue.
Another way is reading a blocks of 1024 bytes from the end of file towards the beginning. Stop when you find n \n characters and print out the last n lines.
You can have two file pointers initially pointing to beginning of file.
Keep on incrementing first pointer till it find '\n' character also stores the instance of file pointer when it find '\n'.
Once it find (n+1)th '\n',assign first stored instance of file pointer which we previously saved,to second file pointer.Keep on doing the same till EOF.
So when first file pointer is on EOF,second will be on n '\n' back.Then print all characters from second file pointer to EOF.
So this is solution which can print last n lines in file in single pass.
How about using memory mapped file and scan the file from backward? This eliminates the hard work of updating the buffer window each time every time if the lines happened to be longer than your buffer space. Then, when you found a \n, push the position into a stack. This works in O(L) where L is the number of characters to output. So there is nothing really better than that is it?

How to read 1000 or more columns data from file using c/c++ language?

A data file with 10000 rows and 1000 columns. I want to save a entire line to an array or each column to a variant.
There is a standard function fscanf in C. If use this function, I need write the format 1000 times.
fscanf(pFile, "%f,%f,%f,%f,%f,%f,......", &a[0], &a[1],...,a[999]);
It is almost impossible like this when programming in C.
But, I have no idea to implement it with C language.
Any suggestions or solutions?
And, how to read or extract some of columns data?
Read the file line by line using fgets() into a suitably large buffer. Don't be afraid to use a buffer of 32 KB or something, just to be very sure all the fields fit.
Then parse the line in a loop, perhaps using strtok() or just plain old strtod(). Note that the latter returns a pointer to the first character that was not considered a number; this is where your parsing will continue for the next number. Perhaps you need to add an inner loop to "eat" whitespace (or whatever separators you have).
You could read the file line by line, and then extract the numbers in a loop.

How to read a space delimited file in C using fscanf with restrictions?

I have a file that has float numbers separated by spaces and I want to open the file and use the numbers inside this file for mathematical operations (e.g. average), how would I do this using only the following: fopen, fscanf, fclose, printf/scanf, pointers, if/else/switch/loops? (No arrays).
The number of values in the space delimited file can be any amount.
Without any knowledge of quantity, you will have to read numbers until you encounter end of file, e.g. use a while construct. Keep a running count of the numbers read.
Remember:
Check the return value from
fscanf, which tells how many
values read.
Read one number per loop to get
things working.
Test for EOF after reading from
the file, as reading may trigger an
EOF.
Also check for other possible file
errors.

How to add one line before the last line in C

Hi I am working in C on Unix platform. Please tell me how to append one line before the last line in C. I have used fopen in appending mode but I cant add one line before the last line.
I just want to write to the second last line in the file.
You don't need to overwrite the whole file. You just have to:
open your file in "rw" mode,
read your file to find the last line: store its position (ftell/ftello) in the file and its contents
go back to the beginning of the last line (fseek/fseeko)
write whatever you want before the last line
write the last line.
close your file.
There is no way of doing this directly in standard C, mostly because few file systems support this operation. The easiest way round this is to read the file into an in memory structure (where you probably have it anyway), insert the line in memory, then write the whole structure out again, overwriting the original file.
Append only appends to the end, not in the middle.
You need to read in the entire file, and then write it out to a new file. You might have luck starting from the back, and finding the byte offset of the second-to-last linefeed. Then you can just block write the entire "prelude", add your new line, and then emit the remaining trailer.
You can find the place where the last line ends, read the last line into memory, seek back to the place, write the new line, and then the last line.
To find the place: Seek to the end, minus a buffer size. Read buffer, look for
newline. If not found, seek backwards two buffer sizes, and try again.
You'll need to use the r+ mode for fopen.
Oh, and you'll need to be careful about text and binary modes. You need to use binary mode, since with text mode you can't compute jump positions, you can only jump to locations you've gotten from ftell. You can work around that by reading through the entire file, and calling ftell at the beginning of each line. For large files, that is going to be slow.
Use fseek to jump to end of file, read backwards until you encounter a newline. Then insert your line.
You might want to save the 'last line' you are reading by counting how many chars you are reading backwards then strncpy it to a properly allocated buffer.

Resources