Click here to Skip to main content
15,891,409 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.


C++
#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;
}


What I have tried:

After reading from the file, If I call fseek() to reset the file descriptor, the code works well.
Posted
Updated 27-Feb-16 3:42am
Comments
Patrice T 27-Feb-16 9:29am    
What is the question ?

1 solution

See fopen[^]:
Quote:
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.
 
Share this answer
 
Comments
LubinLewCHN 27-Feb-16 10:07am    
Thanks,the codes do the work after calling fseek(fp, 0, SEEK_CUR).
Arthur V. Ratz 21-Mar-16 2:18am    
5.
Arthur V. Ratz 20-Mar-16 11:32am    
Also you can use the file contents mapping into a buffer using mmap function.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900