I am trying to finally learn C but I am getting stuck with some stupid things. In this case, what I am trying to achieve, is to create a program that will manage phone contacts. The "tool" allows to insert a contact or delete and search for contacts. It uses a binary file in C and I configured the code so it will work with records and fields of variable length. In this case, my records are in the following format (there is a header that points to the last deleted record):
record_length|name|phone|
My current requirement is that when I choose to delete a record, I will overwrite the record contents with:
record_length * next_record*
This token *
identifies that the record status is deleted. Until this point, I am ok with the program. The problem is about a last function of the program, which is compress file
.
I want to add a function that will read the whole file and copy the VALID records to a new file, removing any unused space (for example, if I delete a record with length of 20 and later or if I overwrite the record with a new one with length 10, the process will keep the last 10 junk chars in the file).
The function is actually pretty simple, the basic idea is:
- Go to the beginning of my file and read the header to store it in a temporary variable
fread
from file withsizeof(int)
to get the record length untilfread
returnsNULL
(end of file)fread
one single characterif this char == *
, I want to skip the record and move to the nextelse
, go back 1 position in the file and copy the valid chars of the record to the new file.
And now comes the stupid question: how do I verify, wether the character is an asterisk? I am so frustrated because I was able to implement the whole code, the only thing that I am missing is this this implementation. Here is what I am trying to do:
#define MAX_REGI_SZ 70 int main (void) { char registro[MAX_REGI_SZ]; ... ... ... fread(registro,sizeof(char),1,in); if (strcmp(registro,"\*")) { /* move to the next record */ } else { /* valid record, copy it over to the new file */ } ... }
I have already tried to compare with
"*"
, tried to declare a char token and thenmake token = "*"
and then use token in thestrcmp
, tried to compareregistro == "*"
directly, this is simply impossible to achieve. I have been trying to find a solution to this for days and haven't found anything anywhere, so I am giving up and asking here to the masters of C.