如何不在开头或结尾处写入文件 [英] How to write a file not at the start or tail

查看:129
本文介绍了如何不在开头或结尾处写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"Test.txt"的文件,其中包含一个简单的字符串"0123456789".
看一下代码,
1.以"r +"模式打开文件//读取和写入
2.从文件读取3个字节
3.在第3个字节的位置写入10个字节
==>问题:仅可以向文件写入7个字节,并且文件未更改.


I have a exist file named "Test.txt" which contents a simple string "0123456789".
Look at the code,
1.open the file in the mode "r+" //read and write
2.read 3 bytes from the file
3.at the the 3rd byte position, write 10 bytes
==>Problem:just can write 7 bytes to file, and the file not changed.


#include <stdio.h>

int main(void)
{
	FILE* fp = fopen("Test.txt", "r+");
	char ReadBuff[3] = {0};
	int ReadLength = fread(ReadBuff, 1, 3, fp); //ReadLength=3
	int FpPos = ftell(fp); //FpPos=3
	char WriteBuff[10] = {0};
	char* Str = "abcdefghij"; //10 bytes
	int WriteLength = fwrite(Str, 1, 10, fp);//WriteLength=7
	
	fclose(fp);
	return 0;
}



我尝试过的事情:

从文件读取后,如果我调用fseek()重置文件描述符,则代码运行良好.



What I have tried:

After reading from the file, If I call fseek() to reset the file descriptor, the code works well.

推荐答案

请参见 ^ ]:
See fopen[^]:
引用:

以更新模式打开文件时(模式参数中的第二个或第三个字符"+"),两个都输入并且可以在相关的流上执行输出.但是,应用程序应确保在没有中间调用fflush()或文件定位函数(fseek(),fsetpos()或rewind())的情况下,输出后不直接跟随输入,并且输入后不直接跟随除非输入操作遇到文件结尾,否则输出不会介入文件定位函数.

When a file is opened with update mode ( ''+'' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, the application shall ensure that output is not directly followed by input without an intervening call to fflush() or to a file positioning function ( fseek(), fsetpos(), or rewind()), and input is not directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.


这篇关于如何不在开头或结尾处写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆