开发者

Overwrite file using append mode for fopen

I am using fopen to write to a binary file and using the cstdio (stdio.h) library due to legacy code and it must be cross-platform compatible with Windows and Linux.

For the prototype, FILE * fopen ( const char * filename, const char * mode );, I am using const char * mode = "ab", which will append to a binary file. Writing operations append data at the end of the file. The file is created if it does not exist.

I have N number of input files where I process data from and write to one output file for each type, where I have M types. I process one input file and write the data to each corresponding output file. I then will close that ith input file and open (i + 1)th, and repeat the process by appending the data from the input file to the output files.

If an output file exists at the beginning on the executable, I want it deleted. If it exists and I don't delete it, then when I use the "wb" mo开发者_如何转开发de, then it will just append data to the output file, which will result in duplication I don't want. I am open to a boost solution and I like to maintain standards best as possible (i.e avoid POSIX if possible)

fopen C++ reference


Here is one way

char* infile[N] = //input names
char* outfile[M] = //output names

int i, j;
for (i = 0; i < N; i++){
  //process input
  char* mode = "ab";
  if (i == 0) mode = "wb";
  for (j = 0; j < M; j++){
    FILE* f = fopen(outfile[j], mode);
    //write to file
    fclose(f);
  }
}

The "w" mode should overwrite the file. It is "a" mode that will avoid deleting a file that already exists.

EDIT: You can also remove (const char * filename) if you want to delete the files at the beginning of execution. If that's the case then you never have to use the "wb" mode.


One possibility would be to use open (_open for Windows) to create the appropriate file handle and then use fdopen (_fdopen for Windows) to create a stdio handle out of it. You will need some preprocessor magic to handle the fact that the names are not exactly the same in Linux and Windows:

// Allow us to use Posix compatible names on Windows
#ifdef WINDOWS
#define open      _open
#define O_CREAT   _O_CREAT
#define O_TRUNC   _O_TRUNC
#define O_APEND   _O_APPEND
#define S_IREAD   _S_IREAD
#define S_IWRITE  _S_IWRITE
#define fdopen    _fdopen
#endif

int fd = open(filename, O_CREAT | O_TRUNC | O_APPEND, S_IREAD | S_IWRITE);
FILE *fp = fdopen(fd, "a");


If you want to overwrite rather than append, why not just use the mode "wb"? "w" overwrites the file when writing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜