简体   繁体   中英

c - How to delete specific strings/files in a file?

I am getting acquainted with C right now and have a bit of a problem with deleting a specific file or string in another file(system).

What I am essentially doing is building a virtual filesystem, where you can add files, search or delete them.

I can't seem to get the last part to work and google doesn't give me any usable results ("how to delete a file in c").

What I got so far:

void deleteFILE(){
FILE *f = fopen ("myfilesystem.nfo", "r+");
if(f == 0) {
    perror("DANGER");
    return;
}
    char *del;
    printf (" You deleted the file: %s", del);

}

Would be awesome if someone could help me or point me in the right direction.

You are asking how to delete content from a file. There are two scenarios:

  1. If you wish to delete content from some point in the file up to the end, you can use truncate or ftruncate if you are on a POSIX system. Non POSIX systems have similar functions to perform this task, but so far as I know there is nothing in the C standard library that truncates files.

  2. If you wish to delete content from the middle of the file you need to copy the file contents that follows the deleted part over the top of the deleted part. And then you need to truncate the file to its new length.

As an example to make this clear this file:

Pos:          0123456789
File content: abcdefghij

Suppose that you wished to delete bytes 7-9, hij. Then you would simply truncate the file to have length 7. This is scenario 1 above.

If you wished to delete bytes 2-6, cdefg, then you would do the following:

  • Copy bytes 7-9 onto position 2.
  • Truncate the file to have length 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM