【发布时间】:2018-07-13 03:56:49
【问题描述】:
我的意图是读取第一行中的第二个元素并将其替换为我们作为命令行参数传递的值并在 input.txt 文件中替换它
输入文件:logic.txt
一个=1234
两个=3456
我希望我的文件在编译完代码后可以这样更改。
./a.out 1567
目前我得到这样的输出
./filelogic 1567
1567=1234
两个=5678
编译后预期的输出文件应该这样修改
逻辑.txt
一个=1567
两个=5678
char buf[MAXSIZE] = {};
int num = 0;
int i = 0;
num = atoi(argv[1]);
printf("%d",num);
FILE *fp1;
fp1 = fopen("logic.txt","r");//currently reading the file.
if(fp1 != NULL)
{
fseek(fp1,3,0);//Need to Move the pointer to the 3rd position where i need to replace the num(fseek(fp1,??,0))-->how we can achieve that.
//Using which method i can replace the num value into a file (means need to replace 1234 inplace of 1567)
//Once the changes are done need to replace in the same file.
fread(buf, 1, MAXSIZE, fp1);
printf("%s\n",buf);
fclose(fp1);
}else {
printf("Cannot open file"");
exit(1);
}
有人可以指导我解决这个问题吗?提前致谢
【问题讨论】:
-
文件中的替换(也称为覆盖)要求新旧内容具有完全相同的长度。否则,您必须读取旧文件并写入新文件,从而替换您想要的文件,或者将文件读入内存缓冲区,替换内容(可能会移动部分缓冲区内容)并从内存缓冲区重写文件。当然,对于后者,缓冲区必须有足够的大小来容纳替换前后的文件内容。
标签: c