Search code examples
ctextseparator

How to check for "separators" in text files?


I am starting the development of a new program (for school project) in which users login and have a "timeline" like page. For now it's a simple command line C project.

I would like to store the data in text files in the following way:

#    
Message here Message here Message here Message here Message here Message here
Message here Message here Message here Message here Message here Message here
Message here Message here Message here Message here Message here Message here
#
Message2 here Message2 here Message2 here Message2 here Message2 here Message2 here 
Message2 here Message2 here Message2 here Message2 here Message2 here Message2 here
#
...etc 

I know how to store the data, it would just be a "write at the end" function. My question relates to the reading of that file. I want to be able to check for the "#" character or whatever character i put to separate the messages and read the message, store it in a structure, show it in the command line and then go on to the next marker, show the message2 and so on.

Is there a "good" or should i say improved way of doing this in C ?

I'm sorry if there is no real code here, i'm just thinking ahead before actually starting the code.

A big thank you in advance to anybody who will help or at least try!


Solution

    1. You can read the whole file to one variable (must be big enough, so you have to use dynamic memory allocation) and then 'divide' it to separate messages using function strtok and character # as separator.

    2. You can simply start reading the file char after char and save it to one variable, and when your current char is # then the variable will store exactly 1 message and you can proceed reading the next message and save it to the new variable, or wherever you want to store it.

    There are many ways to do that, just pick one that is the most suitable for you.