在c中跳转到想要的行并覆盖其中的第一个字母
你好,我正在尝试使用 C 编程语言以所需的行号写入文件 由于某些未知的原因它没有被写入 这是我的检查代码:
int main()
{
int x;
int counter = 0;
char buffer[MAX];
FILE* fp = fopen("sale_day.txt","w");
fprintf(fp,"5 orange 11\n");
fprintf(fp,"4 pelephone 222\n");
fprintf(fp,"3 mirs 4000\n");
fprintf(fp,"2 cellcom 302\n");
fprintf(fp,"1 tmobile 500\n");
fclose(fp);
fp = fopen("sale_day.txt","r+");
while (counter < 2)
{// jumping two rows
fgets(buffer,MAX,fp);// i tried using fscanf which didnt help aswell
counter++;
}
fflush(fp); // i tried with and without still doesnt work
fputs("$",fp);
fflush(fp); // i tried with and without still doesnt work
fclose(fp);
}
我希望得到:
5 orange 11
4 pelephone 222
$ mirs 4000
2 cellcom 302
1 tmobile 500
出于某种原因,它在“sale_day.txt”文件中保持如下内容,
5 orange 11
4 pelephone 222
3 mirs 4000
2 cellcom 302
1 tmobile 500
即使当我调试它时它显示“$”而不是 3 位数字,
提前感谢您的帮助!
hello i am trying to write to a FILE in a wanted line number using c programming language
and for some unknown reasons it doesnt get written
this is my checking code:
int main()
{
int x;
int counter = 0;
char buffer[MAX];
FILE* fp = fopen("sale_day.txt","w");
fprintf(fp,"5 orange 11\n");
fprintf(fp,"4 pelephone 222\n");
fprintf(fp,"3 mirs 4000\n");
fprintf(fp,"2 cellcom 302\n");
fprintf(fp,"1 tmobile 500\n");
fclose(fp);
fp = fopen("sale_day.txt","r+");
while (counter < 2)
{// jumping two rows
fgets(buffer,MAX,fp);// i tried using fscanf which didnt help aswell
counter++;
}
fflush(fp); // i tried with and without still doesnt work
fputs("$",fp);
fflush(fp); // i tried with and without still doesnt work
fclose(fp);
}
i expect to get :
5 orange 11
4 pelephone 222
$ mirs 4000
2 cellcom 302
1 tmobile 500
for some reason it stays as the following in "sale_day.txt" file
5 orange 11
4 pelephone 222
3 mirs 4000
2 cellcom 302
1 tmobile 500
even tho when i debug it it shows a "$" instead of the 3 digit
thanks in advance for your help !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码工作得很好,也没有
fflush
行。运行程序后,第 3 行更改如下:之前:
3 mirs 4000
之后:
$ mirs 4000
我按原样运行了您的代码,只是在上面添加了以下内容:
The code works just fine, also without the
fflush
-lines. After running the program, line 3 is changed as follows:Before:
3 mirs 4000
After:
$ mirs 4000
I ran your code like it is, only with this on top:
你在期待什么?当我运行您的代码时,我得到:
考虑到您的编码,这是完全正确的:读取两行(让您位于第三行),然后写入一个
$
字符。请注意,文件写入操作会覆盖现有文件数据,或将新数据附加到文件末尾。它们不会插入数据(这可能是您期望的操作)。
What are you expecting? When I run your code, I get:
This is exactly right given what you've coded: read two lines (leaving you positioned at the third line), and write a
$
char.Note that file write operations overwrite existing file data, or append new data to the end of a file. They don't insert data (which may have been the operation you're expecting).