C语言fwrite函数不能写入文件的原因记录

最近在写一个C语言的小程序,中间需要对文件进行读写操作,使用到了fwrite函数,示例代码如下:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
	const char* fileName = "./test.bin";
	FILE* tarFile;

	int i,j;
	short tarSource[10]={0,0,0,0,0,0,0,0,0,0};

	tarFile = fopen(fileName,"wb+");	//打开文件
	for(i=0;i<10;i++)
	{
		fread(tarSource,2,10,tarFile);	//读取二进制文件
		for(j=0;j<10;j++)
		{
			tarSource[j]+=1;
		}
		fseek(tarFile,0,SEEK_SET);		//移动流到文件头
		fwrite(tarSource,2,10,tarFile);	//二进制写入文件
	}
	fclose(tarFile);					//关闭文件
}

期望最后的文件内容如下:
期望的结果
但是以上代码运行出来的内容如下:
实际运行结果

百思不得其解之后终于在度娘上找到问题的原因[1],原来fopen函数在使用"r+"、"w+"或"a+"对文件进行读写时,在fwrite和fread之间必须插入fflush、fsetpos、fseek或rewind函数,否则将无法写入。详细说明如下:

"r"
Opens for reading. If the file does not exist or cannot be found, the fopen call fails.
"w"
Opens an empty file for writing. If the given file exists, its contents are destroyed.
"a"
Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn’t exist.
"r+"
Opens for both reading and writing. (The file must exist.)
"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.
"a+"
Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn’t exist.
When a file is opened with the “a” or “a+” access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.
The “a” mode does not remove the EOF marker before appending to the file. After appending has occurred, the MS-DOS TYPE command only shows data up to the original EOF marker and not any data appended to the file. The “a+” mode does remove the EOF marker before appending to the file. After appending, the MS-DOS TYPE command shows all data in the file. The “a+” mode is required for appending to a stream file that is terminated with the CTRL+Z EOF marker.
When the “r+”, “w+”, or “a+” access type is specified, both reading and writing are allowed (the file is said to be open for “update”). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.
In addition to the above values, the following characters can be included in mode to specify the translation mode for newline characters:
t
Open in text (translated) mode. In this mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing with “a+”, fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file that ends with a CTRL+Z, may cause fseek to behave improperly near the end of the file.
Also, in text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).
b
Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.
If t or b is not given in mode, the default translation mode is defined by the global variable _fmode. If t or b is prefixed to the argument, the function fails and returns NULL.
For more information about using text and binary modes in Unicode and multibyte stream-I/O, see Text and Binary Mode File I/O and Unicode Stream I/O in Text and Binary Modes.
c
Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or _flushall is called.
n
Reset the commit flag for the associated filename to “no-commit.” This is the default. It also overrides the global commit flag if you link your program with COMMODE.OBJ. The global commit flag default is “no-commit” unless you explicitly link your program with COMMODE.OBJ.

在fwrite和fread之间插入fseek并更新代码后,结果正确:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
	const char* fileName = "./test.bin";
	FILE* tarFile;

	int i,j;
	short tarSource[10]={0,0,0,0,0,0,0,0,0,0};

	tarFile = fopen(fileName,"wb+");	//打开文件
	for(i=0;i<10;i++)
	{
		fread(tarSource,2,10,tarFile);	//读取二进制文件
		for(j=0;j<10;j++)
		{
			tarSource[j]+=1;
		}
		fseek(tarFile,0,SEEK_SET);		//移动流到文件头
		fwrite(tarSource,2,10,tarFile);	//二进制写入文件
		fseek(tarFile,0,SEEK_SET);		//移动流到文件头
	}
	fclose(tarFile);					//关闭文件
}

参考资料

[1] 管与fwrite()函数不能写入文件的问题 https://bbs.youkuaiyun.com/topics/391996778?page=1

### C语言中无法向地址写入值的问题及其解决方案 当遇到C语言中无法向地址写入值的情况时,通常是因为存在非法内存访问或指针使用当等问题。以下是几种常见原因及相应的解决方法。 #### 1. 非法解引用空指针 尝试通过空指针访问或修改其指向位置的数据会导致程序崩溃。应始终确保指针被正确初始化并指向有效的存储区域[^2]。 ```c // 错误示范 int *p = NULL; *p = 10; // 正确方式 int value = 10; int *ptr = &value; *ptr = 20; // 合法操作 ``` #### 2. 数组越界访问 超出数组定义范围的操作会引发未定义行为,包括但限于覆盖其他变量甚至破坏堆栈结构。务必严格控制索引界限,在循环体内加入必要的边界条件判断[^1]。 ```c #include <stdio.h> void safeArrayAccess(int arr[], int length) { for (int i = 0; i < length && i >= 0 ; ++i){ if(i<length){ arr[i]=i*i; } } } int main(){ int numbers[5]; safeArrayAccess(numbers,sizeof(numbers)/sizeof(*numbers)); } ``` #### 3. 缺少适当修饰符导致编译期报错 某些情况下可能是由于语法上的疏忽造成的编译失败,比如忘记给`scanf()`传递参数前加上取地址运算符(&),这将引起编译器报告错误信息提示合法表达式[^3]。 ```c // 错误示范 char str[]="hello"; scanf("%s",&str); // 正确形式 char inputStr[80]=""; scanf("%79s",inputStr); ``` #### 4. 文件IO过程中可能出现的异常情况处理 对于涉及磁盘读的场景下,应当注意检查返回的状态码以及调用相应API确认具体问题所在。特别是针对二进制流传输而言更需谨慎对待每一个细节之处以免造成必要的麻烦[^5]. ```c FILE *filePtr=fopen("example.bin","wb+"); if(!filePtr){ /* handle error */ } size_t result=fwrite(dataBuffer, sizeof(char), bufferSize,filePtr ); if(result!=bufferSize || ferror(filePtr)){ perror("File write failed"); }else{ puts("Data written successfully."); } fclose(filePtr); ``` 为了有效预防此类故障的发生,建议开发者们养成良好的编程习惯: - 使用静态分析工具提前发现潜在隐患; - 开发阶段尽可能启用最高级别的警告级别; - 运行期间开启调试模式以便及时捕捉致命信号; - 定期复习官方文档学习最佳实践案例分享;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值