fread和fwrite同時對一個文件讀寫


這幾天看到了fopen的參數設置。中文的那些真的是不能幫助精確理解。在網上發現了英文的,特附上:

FILE *fopen(const char *filename, const char *mode)
fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include:
"r"
open text file for reading
"w"
create text file for writing; discard previous contents if any
"a"
append; open or create text file for writing at end of file
"r+"
open text file for update (i.e., reading and writing)
"w+"
create text file for update, discard previous contents if any
"a+"
append; open or create text file for update, writing at end
Update mode permits reading and writing the same file; fflush or a file-positioning function must be called between a read and a write or vice versa. If the mode includes b after the initial letter, as in "rb" or "w+b", that indicates a binary file. Filenames are limited to FILENAME_MAX characters. At most FOPEN_MAX files may be open at once.

其中+號表示可讀可寫,即上面的“更新模式”。

對“更新模式”:可以同時讀寫,但是必須有清空緩沖區函數或者文件定位函數。意思是在讀或寫之間得調用文件定位的相關函數,比如fseek,rewind等等。

經我測試確實是這樣。

int main()
{
    FILE *fp = fopen("1.txt", "r+");
    char Rbuf[5], Wbuf[5] = "4321";


    fread(Rbuf, sizeof(char), 4, fp);
    Rbuf[4] = '\0';

    fseek(fp,ftell(fp),SEEK_SET);
    fwrite(Wbuf, sizeof(char), 4, fp);
    printf("%s\n", Rbuf);
    
    fclose(fp);

    return 0;
}

只有這樣,你才能在讀之后接着寫進去文件,或者rewind定位后重頭部寫進去。其他,都不行根本寫不進去。具體原因我也不明白,用ftell測試后也發現對的,但是還是寫不進去。只有這樣可以,可能是什么內部實現吧。

畢竟文件讀寫函數是封裝之后的,還是按它的標准來。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM