文章出處
文章列表
C寫入數據到文件
#include <stdio.h> #include <string.h> int main( ) { FILE* fd = fopen("txt.txt","w+"); char a[] = "abcdefg"; for(int i=0; i<strlen(a); i++ ){ fputc(a[i],fd); }; fclose(fd); return 0; }
寫入一串數據:
#include <stdio.h> int main() { FILE *f = fopen("txt.txt", "a+"); char str[16] = "66666666"; fprintf(f, "%s\n", str); printf("%s", str); fclose(f); return 0; }
mode有下列幾種形態字符串:
r 打開只讀文件,該文件必須存在。
r+ 打開可讀寫的文件,該文件必須存在。
w 打開只寫文件,若文件存在則文件長度清為0,即該文件內容會消失。若文件不存在則建立該文件。
w+ 打開可讀寫文件,若文件存在則文件長度清為零,即該文件內容會消失。若文件不存在則建立該文件。
a 以附加的方式打開只寫文件。若文件不存在,則會建立該文件,如果文件存在,寫入的數據會被加到文件尾,即文件原先的內容會被保留。
a+ 以附加方式打開可讀寫的文件。若文件不存在,則會建立該文件,如果文件存在,寫入的數據會被加到文件尾后,即文件原先的內容會被保留。
上述的形態字符串都可以再加一個b字符,如rb、w+b或ab+等組合,加入b 字符用來告訴函數庫打開的文件為二進制文件,而非純文字文件
通過fopen創建并打開文件:
#include <stdio.h> int main() { FILE *p; p = fopen("txt.txt", "r+"); if( p == NULL ) { printf("open failed\n"); }else{ printf("open success\n"); fclose(p); } return 0; }
fscanf讀取文件并打印:
#include <stdio.h> int main() { FILE *f = fopen("txt.txt", "r+"); char strs[20]; fscanf(f, "%s", strs); printf("stirng is %s\n", strs); return 0; }
使用fgetc獲取一個字符并打印, 循環即可讀取所有字符:
#include <stdio.h> int main() { FILE *p; p = fopen("txt.txt", "r+"); int c; while( (c=fgetc(p))!=EOF ) { printf("%c",c); } return 0; }
使用fwrite和fread也可以實現同樣的效果:
#include <stdio.h> void main( void ) { FILE *stream; char list[30]; int i, numread, numwritten; // 以文本方式打開文件 if( (stream = fopen( "fread.out", "w+t" )) != NULL ) // 如果讀取無誤 { for ( i = 0; i < 25; i++ ) list[i] = (char)('z' - i); numwritten = fwrite( list, sizeof( char ), 25, stream ); printf( "Wrote %d items\n", numwritten ); fclose( stream ); } else { printf( "Problem opening the file\n" ); } if( (stream = fopen( "fread.out", "r+t" )) != NULL ) // 文件讀取 { numread = fread( list, sizeof( char ), 25, stream ); printf( "Number of items read = %d\n", numread ); printf( "Contents of buffer = %.25s\n", list ); fclose( stream ); } else { printf( "File could not be opened\n" ); } }
作者: NONO
出處:http://www.cnblogs.com/diligenceday/
企業網站:http://www.idrwl.com/
開源博客:http://www.github.com/sqqihao
QQ:287101329
微信:18101055830
廈門點燃未來網絡科技有限公司, 是廈門最好的微信應用, 小程序, 微信網站, 公眾號開發公司
文章列表
全站熱搜