[英]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). 我现在已经熟悉C,并且在删除另一个文件(系统)中的特定文件或字符串时遇到了一些问题。
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"). 我似乎无法使最后一部分正常工作,并且google没有给我任何可用的结果(“如何在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:
有两种情况:
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. 如果您希望从文件中的某个点删除内容直到最后,如果您使用的是POSIX系统,则可以使用
truncate
或ftruncate
。 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. 非POSIX系统具有类似的功能来执行此任务,但据我所知,C标准库中没有任何东西可以截断文件。
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. 假设您希望删除字节7-9,hij。 Then you would simply truncate the file to have length 7. This is scenario 1 above.
然后,您只需将文件的长度截短为7。这就是上面的方案1。
If you wished to delete bytes 2-6, cdefg, then you would do the following: 如果您希望删除字节2-6,即cdefg,则可以执行以下操作:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.