简体   繁体   English

如何在C中使用stdio在文件中正确移动查找指针

[英]How do I properly move a seek pointer in a file with stdio in C

I'm messing around with seek pointers in C, and my exercise is to write a database (format: ID NAME SURNAME AGE) into a textfile. 我在弄乱C语言中的查找指针,我的练习是将一个数据库(格式:ID NAME SURNAME AGE)写入文本文件。 So everything works fine (saving new data etc.) but I can't find a solution on how to delete a line in my textfile. 因此,一切正常(保存新数据等),但是我找不到如何删除文本文件中的行的解决方案。

void cut_from_file(char* filename, int start, int stop) {
    FILE *fp = fopen(filename, "w");
    fpos_t position;
    fseek(fp, 34, SEEK_SET);
    fputs("Hello world", fp);
    fclose (fp);
}

Note: I want to make it somehow a random access file. 注意:我想以某种方式使其成为随机访问文件。

So my question would be how can I move the filepointer let's say 34 characters forward and overwrite the characters on that position but leave the characters from position 0 - 33 as they are? 所以我的问题是我该如何移动文件指针,比如说向前移动34个字符并覆盖该位置上的字符,而将位置0-33的字符保留原样?

If I try to do it like on my test function above I overwrite everything from offset 0 - 33 with '/00' and on position 34 is Hello World. 如果我尝试像上面的测试函数那样执行此操作,那么我会使用'/ 00'覆盖偏移量0-33的所有内容,并在位置34处输入Hello World。

fopen(filename, "r+") was the answer, gosh I messed that up pretty hard. fopen(filename,“ r +”)是答案,天哪,我很难搞清楚。

Thanks everyone :) 感谢大家 :)

Use SEEK_CUR instead of SEEK_SET to move forward from the currect index. 使用SEEK_CUR而不是SEEK_SET从当前索引向前移动。 SEEK_SET takes you 34 chars forward from the beginning of the file. SEEK_SET从文件开头开始将您向前移动了34个字符。 Also "w" in opening the file overwrites all its contents. 同样,打开文件时的“ w”将覆盖其所有内容。

There's no way of simply making a chunk of the file disappear. 无法简单地使文件的一部分消失。

The two possible solutions that I can see are: 我看到的两个可能的解决方案是:

  1. Read the whole file in, write it out and skip the line(s) you want to delete. 读入整个文件,将其写出,然后跳过要删除的行。
  2. Use an extra byte (and fixed-width records!) to indicate if an entry is "deleted" or "not deleted". 使用一个额外的字节(和固定宽度的记录!)来指示条目是“已删除”还是“未删除”。 That means deleting a record is a single write and you then know you can re-use the space for another record. 这意味着删除一条记录是一次写入操作,然后您便知道可以将空间重新用于另一条记录。

要从文件中删除一行,您可以打开一个临时文件,并将内容逐行写入其中,然后跳过要删除的行,稍后可以用该临时文件替换原始文件。

(1) Move the last entry to the entry you want to delete. (1)将最后一个条目移至要删除的条目。 (2) Call truncate to shorten the file. (2)调用truncate以缩短文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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