[英]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: 我看到的两个可能的解决方案是:
要从文件中删除一行,您可以打开一个临时文件,并将内容逐行写入其中,然后跳过要删除的行,稍后可以用该临时文件替换原始文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.