跳到一条想要的线并在c中覆盖其中的第一个字母

时间:2011-03-11 11:01:46

标签: c printf

你好我想用c编程语言写一个想要的行号中的FILE 由于一些不明原因,它不会被写入 这是我的支票代码:

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位数

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

代码工作正常,也没有fflush行。运行程序后,第3行更改如下:

在:

3 mirs 4000

后:

$ mirs 4000

我像你一样运行你的代码,只有这一点在顶部:

#include <stdio.h>
#define MAX 255

答案 1 :(得分:0)

你在期待什么?当我运行你的代码时,我得到:

5 orange 11
4 pelephone 222
$ mirs 4000
2 cellcom 302
1 tmobile 500

根据您编码的内容,这是完全正确的:读取两行(让您定位在第三行),然后写一个$字符。

请注意,文件写入操作会覆盖现有文件数据,或将新数据附加到文件末尾。它们不会插入数据(这可能是您期望的操作)。