I'm new here, and I need some help. :)

I am working on a program that has to write and read a binary file. I have to add lectures to it, they look like:


I could write that in a file without any problems using char*.

My question is: how do I read that back in a struct if the records are non-fixed size? (e.g.: coursename can be Linear Algebra or Analysis -> length is non-determined) I also need to modify the actual applicants number, how do I find the character position of it, and the current line?

I'd be happy with ideas, and I would appreciate any source code as well, I was programming in C++ and C is a hard step-back for me.

Thank you in advance!

3 Years
Discussion Span
Last Post by Banfa

You have a couple of options.

  1. Read the whole line using getline into a std::string and use the various members of std::string to parse the line into the individual data members of your structure
  2. Use the delimiter parameter of getline to read up to the ; delimiter in your data lines

You can use the following functions :
1. strtok to parse strings seperated by a token (';' in your case).
2. strcmp to compare if two strings are the same.

In a while loop you can use strtok to get each of your records' data and use a counter variable which will be increased every time you find the newline character ('\n').
Using strcmp you can compare each token with the string you are searching. The loop counter will have the line you are positioned in that case.
As for the column of the line you could use strlen on each token and add the lengths of the strings to get the column you are trying to alter.

Hope that helped!

Edited by ktsangop


How do I use std::string? Isn't that "C++ only"? If I search it in Google I can't really find any C related websites about it, only string methods as you mentioned like strtok and strcmp. Or just make a char* chstring, getline(chstring), and then parse it as you mentioned?

Thanks and sorry for the stupid questions ^^


Sorry about that I missed that the thread was in the C not the C++ forum.

Be careful with strtok, it is very non-reentrant and I would avoid it altogether if you are writing a multi-threaded application. You can always do what strtok does with some fairly simple pointer manipulation.

You can read the file line by line with fgets.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.