本文介绍了fseek在写入值时返回到文件结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在文件的位置4覆盖4个字节,但fseek似乎不工作。



我的代码:

  int r = fseek(cacheStream,4,SEEK_SET); 
std :: cout<< fseek returns<< r<< std :: endl;
std :: cout<< ftell< ftell(cacheStream)<< std :: endl;
r = fwrite(& chunckSize,sizeof(uint32_t),1,cacheStream);
std :: cout<< fwrite返回< r<< std :: endl;
std :: cout<< ftell< ftell(cacheStream)<< std :: endl;

cacheStream以ab打开。输出为:

  fseek返回0 
ftell 4
fwrite返回1
ftell 2822716

值未被覆盖,而是写入文件末尾。

解决方案

ab模式意味着每个写入将被附加到文件,而不管写入之前的位置。



如果你不想要,不要使用<$ :







$ b

如果您打开一个现有文件进行更新,r + b打开文件进行读写; w + b在打开文件时截断文件,但允许您阅读已编写的内容。



C99标准(ISO / IEC 9899:1999 - 不是当前的标准,但非常相似)说:


I am trying to override 4 bytes at position 4 in a file, but fseek seems not to be working.

My code:

int r = fseek(cacheStream, 4, SEEK_SET);
std::cout << "fseek returns " << r << std::endl;
std::cout << "ftell " << ftell(cacheStream) << std::endl;
r = fwrite(&chunckSize, sizeof(uint32_t), 1, cacheStream);
std::cout << "fwrite returns " << r << std::endl;
std::cout << "ftell " << ftell(cacheStream) << std::endl;

cacheStream was open with "ab". The output is:

fseek returns 0
ftell 4
fwrite returns 1
ftell 2822716

The value was not overriden, but instead it was written at the end of file. What could cause that weird behaviour with fseek?

解决方案

The "ab" mode means that every write will be appended to the file, regardless of position before the write.

If you don't want that, don't use the "a" flag.

Added later:

If you're opening an existing file for update, then "r+b" opens the file for reading and writing; "w+b" truncates the file when it is opened, but allows you to read what you've written.

The C99 standard (ISO/IEC 9899:1999 — not the current standard, but that will be very similar) says:

这篇关于fseek在写入值时返回到文件结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:34