用 C 覆盖文件中的行
我正在大学操作系统课程中做一个关于文件系统的项目,我的C程序应该在人类可读的文件中模拟一个简单的文件系统,所以文件应该基于行,一行将是一个“扇区”。我了解到,要覆盖的行必须具有相同的长度,因此我将用 ASCII 零填充它们,直到行尾,并留下一定数量的 ASCII 零行,以便稍后填充。
现在我正在制作一个测试程序,看看它是否像我想要的那样工作,但事实并非如此。我的代码的关键部分:
file = fopen("irasproba_tesztfajl.txt", "r+"); //it is previously loaded with 10 copies of the line I'll print later in reverse order
/* this finds the 3rd line */
int count = 0; //how much have we gone yet?
char c;
while(count != 2) {
if((c = fgetc(file)) == '\n') count++;
}
fflush(file);
fprintf(file, "- . , M N B V C X Y Í Ű Á É L K J H G F D S A Ú Ő P O I U Z T R E W Q Ó Ü Ö 9 8 7 6 5 4 3 2 1 0\n");
fflush(file);
fclose(file);
现在它什么也不做,文件保持不变。可能是什么问题?
谢谢。
I'm doing a project on filesystems on a university operating systems course, my C program should simulate a simple filesystem in a human-readable file, so the file should be based on lines, a line will be a "sector". I've learned, that lines must be of the same length to be overwritten, so I'll pad them with ascii zeroes till the end of the line and leave a certain amount of lines of ascii zeroes that can be filled later.
Now I'm making a test program to see if it works like I want it to, but it doesnt. The critical part of my code:
file = fopen("irasproba_tesztfajl.txt", "r+"); //it is previously loaded with 10 copies of the line I'll print later in reverse order
/* this finds the 3rd line */
int count = 0; //how much have we gone yet?
char c;
while(count != 2) {
if((c = fgetc(file)) == '\n') count++;
}
fflush(file);
fprintf(file, "- . , M N B V C X Y Í Ű Á É L K J H G F D S A Ú Ő P O I U Z T R E W Q Ó Ü Ö 9 8 7 6 5 4 3 2 1 0\n");
fflush(file);
fclose(file);
Now it does nothing, the file stays the same. What could be the problem?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从此处,
因此,您已经使用
fflush
实现了这一目标,但为了写入所需的位置,您需要fseek
返回。这就是我实现它的方式 - 我想可能会更好:另外,正如所评论的那样,您应该检查您的文件是否已成功打开,即在读取/写入
文件
之前,检查:From here,
So you've achieved that with
fflush
, but in order to write to the desired location you need tofseek
back. This is how I implemented it - could be better I guess:Also, as has been commented, you should check if your file has been opened successfully, i.e. before reading/writing to
file
, check: