在c中将数据插入文件
我需要在现有文件中的第 45 个字节之前添加一个字符串。我尝试使用 fseek
,如下所示。
int main()
{
FILE *fp;
char str[] = "test";
fp = fopen(FILEPATH,"a");
fseek(fp,-45, SEEK_END);
fprintf(fp,"%s",str);
fclose(fp);
return(0);
}
我预计这段代码会在 EOF 的第 45 个th 字符之前添加“test”,相反,它只是将“test”附加到 EOF。
请帮助我找到解决方案。
这是我之前问题的延续
将项目附加到 c 中最后一行之前的文件
I need to add a string before the 45th byte in an existing file. I tried using fseek
as shown below.
int main()
{
FILE *fp;
char str[] = "test";
fp = fopen(FILEPATH,"a");
fseek(fp,-45, SEEK_END);
fprintf(fp,"%s",str);
fclose(fp);
return(0);
}
I expected that this code will add "test" before the 45th char from EOF, instead, it just appends "test" to the EOF.
Please help me to find the solution.
This is continuation of my previous question
Append item to a file before last line in c
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用模式 r+ (如果它已经存在)或 a+ (如果它不存在并且您想创建它)打开它。由于您正在寻找文件末尾之前的 45 个字节,因此我假设它已经存在。
你的其余代码都很好。另请注意,这不会插入文本,但会覆盖文件中当前该位置的任何内容。
即,如果您的文件如下所示:
那么运行此代码后,它将如下所示:
如果您确实想要插入而不是覆盖,那么您需要将从 SEEK_END-45 到 EOF 的所有文本读取到内存中,写入 < em>测试然后写回文本
Open it with mode r+ (if it already exists) or a+ (if it doesn't exist and you want to create it). Since you're seeking to 45 bytes before the end of file, I'm assuming it already exists.
The rest of your code is fine. Also note that this will not insert the text, but will overwrite whatever is currently at that position in the file.
ie, if your file looks like this:
Then after running this code, it will look like this:
If you really want to insert and not overwrite, then you need to read all the text from SEEK_END-45 to EOF into memory, write test and then write the text back
如果您打算在任意位置写入,请勿将其作为附加 (
a
) 打开;它将强制所有写入到文件末尾。您可以使用r+
在任何地方读取或写入。Don't open it as append (
a
) if you plan to write at arbitrary positions; it will force all writes to the end of the file. You can user+
to read or write anywhere.为了避免特定于平台的配置,请始终在 fopen() 调用中明确指示二进制或文本模式。
如果有一天您移植代码,这将为您节省数小时的绝望时间。
To avoid platform-specific configurations, always explicitely indicate the binary or text mode in your fopen() call.
This will save you hours of desperations if you port your code one day.