Monday, 15 June 2015

c - The use of "r+" in fopen on windows vs linux -



c - The use of "r+" in fopen on windows vs linux -

i toying around code opening, reading, , modifying text file. quick (simplified) illustration be:

#include <stdio.h> int main() { file * fp = fopen("test.txt", "r+"); char line[100] = {'\0'}; int count = 0; int ret_code = 0; while(!feof(fp)){ fgets(line, 100, fp); // processing on line... count++; if(count == 4) { ret_code = fprintf(fp, "replaced line\n"); printf("ret code %d\n", ret_code); perror("error was: "); } } fclose(fp); homecoming 0; }

now on linux, compiled gcc (4.6.2) code runs, , modifies file's 5th line. same code, running on windows7 compiled visual c++2010 runs , claims have succeeded (reports homecoming code of 19 characters , perror says "no error") fails replace line.

on linux file has total permissions:

-rw-rw-rw- 1 mike users 191 feb 14 10:11 test.txt

and far can tell it's same on windows:

test.txt (right click) -> properties -> security "allow" checked read & write user, system, , admin.

i same results using mingw's gcc on windows know it's not visual c++ "feature".

am missing obvious, or fact no errors, no output undocumented "feature" of using r+ fopen() on windows?

edit: seems @ microsoft's site "r+" should open reading and writting. made note:

when "r+", "w+", or "a+" access type specified, both reading , writing allowed (the file said open "update"). however, when switch between reading , writing, there must intervening fflush, fsetpos, fseek, or rewind operation. current position can specified fsetpos or fseek operation, if desired.

so tried:

... if(count == 4) { fflush(fp); ret_code = fprintf(fp, "replaced line\n"); fflush(fp); printf("ret code %d\n", ret_code); ...

to no avail.

according linux man page fopen():

reads , writes may intermixed on read/write streams in order. note ansi c requires file positioning function intervene between output , input, unless input operation encounters end-of-file. (if status not met, read allowed homecoming result of writes other recent.) hence practice (and indeed necessary under linux) set fseek(3) or fgetpos(3) operation between write , read operations on such stream. operation may apparent no-op (as in fseek(..., 0l, seek_cur) called synchronizing side effect.

so, should phone call fseek() (as, eg. fseek(..., 0, seek_cur)) when switching between reading , writing file.

c linux windows file-io fopen

No comments:

Post a Comment