fclose关闭文件后怎么再打开同一个文件到某个偏移位置再写
大家好,本人的问题是:
由于本人需要写多个.cpp文件,其中每个.cpp文件中都需要向同一个文件写数据,所以我采用fopen函数
打开文件,fwrite函数写数据。问题是,比如1.cpp中写了数据到文件file.txt,然后fclose关闭。当2.cpp文件
向file.txt文件写数据时,只能是按照fopen函数的"ab"或"wb"的方式,要么是在最后位置写,要么是将原来的数据清零后重新写,而不能用fseek函数定位到指定位置写入数据。 本人猜想是由于fclose释放了所有文件资源的缘故,但是如果我要实现文件定位怎么办,难道是打开文件后就一直不关闭? 求赐教,谢谢~~ c/c++? 数据 文件操作
[解决办法]
二进制方式读写文件操作而已!
每次打开文件关闭文件后,再打开的话,文件读指针就在文件开头了!所以覆盖是正常的!
所以第二次打开文件的时候可以用fseek来偏移指针的!或者可以打开写操作后,不立即关闭文件,继续写操作最好,最后写完再关闭,节约系统调用的消耗
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.
For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters.
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.
c
Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if fflush or _flushall is called.
n
Reset the commit flag for the associated filename to "no-commit." This is the default.
[解决办法]
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, or fseek operation.
The current position can be specified for the fsetpos or fseek operation.
推荐使用WinHex软件查看硬盘或文件或内存中的原始字节内容。
不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待
和
fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
[解决办法]
用 ftell() 记住偏移位置,下次打开后用 fseek() 重新定位