fread 和 fwrite 不能接連着使用,一般要在他們中間加fseek, 這是爲了保持與之前程序的向下兼容性。spa
如如下程序,不管加不加fseek,都能編譯而且執行經過,fread和fwrite都表示完成了任務。然而實際上,若是沒有fseek這句話,fwrite並無將字符寫入文件。code
#include <cstdio> #include <cstdlib> using namespace std; int main() { FILE *fp = fopen("test.txt", "r+"); if (NULL == fp) { fprintf(stderr,"open file \"test.txt\" failed"); exit(1); } char buf[256] = {0}; size_t byteRead = fread(buf, sizeof(char), 10, fp); for (int i=0; i<byteRead; i++) { if (buf[i] > 'a' && buf[i] < 'z') { buf[i] = buf[i] + 'A' - 'a'; } } //fseek(fp, -10, 1); size_t byteWrite = fwrite(buf, sizeof(char), byteRead, fp); if (byteRead != byteWrite) { fprintf(stderr, "read and write error"); exit(1); } fclose(fp); return 0; }