C语言 将数据插入到c中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3264495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting data to file in c
提问by arun
I need to add a string before the 45thbyte in an existing file. I tried using fseekas shown below.
我需要在现有文件的第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);
}
I expected that this code will add "test" before the 45thchar from EOF, instead, it just appends "test" to the EOF.
我希望这段代码会在EOF 的第45个字符之前添加“测试” ,相反,它只是将“测试”附加到 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
这是我上一个问题的延续,
在 c 中的最后一行之前将项目附加到文件
回答by bluesmoon
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.
使用模式 r+(如果它已经存在)或 a+(如果它不存在并且您想创建它)打开它。由于您在文件结束之前寻找 45 个字节,因此我假设它已经存在。
fp = fopen(FILEPATH,"r+");
The rest of your code is fine. Also note that this will not insertthe text, but will overwrite whatever is currently at that position in the file.
你的其余代码很好。另请注意,这不会插入文本,但会覆盖文件中当前位于该位置的任何内容。
ie, if your file looks like this:
即,如果您的文件如下所示:
xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
Then after running this code, it will look like this:
然后运行此代码后,它将如下所示:
xxxxxxxtestxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
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 testand then write the text back
如果你真的想插入而不是覆盖,那么你需要将SEEK_END-45到EOF的所有文本读入内存,写测试然后将文本写回
回答by Matthew Flaschen
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 use r+to read or write anywhere.
a如果您打算在任意位置写入,请不要将其作为 append ( )打开;它将强制所有写入文件的末尾。您可以使用它r+在任何地方读取或写入。
回答by Pierre
To avoid platform-specific configurations, always explicitely indicate the binary or text mode in your fopen() call.
为避免特定于平台的配置,请始终在 fopen() 调用中明确指示二进制或文本模式。
This will save you hours of desperations if you port your code one day.
如果您有一天移植代码,这将为您节省数小时的绝望。

