removing a line from a binary file

Sep 26, 2011 at 12:32pm
Hallo
I am programming with c language in Linux.
anyway i have to define a function that takes a binary file or a pointer of it and change the file by that, that it romoves line number X from it.
that is my function:
//(every 6 charechters are one line)
//filesize is the size of the file


void remove(FILE *fp,long X,long filesize)
{
FILE *fp1=fopen("permanent.lst","wb");
long i=0;
while(i<filesize)
{
unsigned char hex[6] = {0};
fseek(fp,i,SEEK_SET);
if(i!=(X-1))
{
fread(hex, 1, 6, fp);
fwrite(hex, 1, 6, fp1);
}
i++;
}
fp=fopen("permanent.lst","rb");
}

can anyone tell me what is wrong here?? because my code dosent work anymore
Sep 26, 2011 at 9:01pm
closed account (DSLq5Di1)
Does your number of characters per line include the new line character? and why use fseek in your loop? fread will move the file pointer to the next read position for you..
Sep 27, 2011 at 9:19am
thanks for replying man
the number of characters per line does not include the new line character.
i am using fseek because i dont want to read the line number (X-1) i could also define a counter that after every round in the loop it increments in 1, and when it is equal to X-1 i dont read from the file.
Sep 27, 2011 at 10:34pm
closed account (DSLq5Di1)
Reading the line is not a problem, writing it back is what you want to avoid. I'd rewrite your loop as follows,

1
2
3
4
5
6
7
8
9
10
11
12
13
...
unsigned char hex[7] = {0}; // +1 for the new line character
                            // (assuming you are only handling linux text files)
while (!feof(fp))
{
    size_t n = fread(hex, 1, 7, fp);

    if(i!=(X-1))
    {
        fwrite(hex, 1, n, fp1);
    }
    i++
}


You should also close your files when you are done using them,
http://www.cplusplus.com/reference/clibrary/cstdio/fclose/

.. and if C isn't some silly requirement, have a look at using C++ fstreams instead,
http://www.cplusplus.com/reference/iostream/fstream/
Sep 28, 2011 at 7:46am
thanks man i will try it
Topic archived. No new replies allowed.