Linux——fopen、fread、fwrite函式的使用
阿新 • • 發佈:2019-01-01
例子:
#include <stdio.h>
#include <string.h>
/* 寫檔案測試函式 */
static void fwrite_demo()
{
FILE *fp; /* 檔案識別符號 */
char str[64]; /* 字串 */
int str_len; /* 字串長度 */
int num; /* 寫入的長度 */
memset(str, 0, sizeof(str));
strcpy(str, "Insist on yourself;never imitate.Every great man is unique!" );
str_len = strlen(str);
/* 方法1 ---> */
fp = fopen("file_1.txt", "wb+");
if(NULL == fp){
printf("open file error!\n");
}
if (1 != fwrite(str, str_len, 1, fp)){
printf("fwrite error!\n");
}
fclose(fp);
/* <--- 方法1 > */
/* 方法2 ---> */
fp = fopen("file_2.txt" , "wb+");
if(NULL == fp){
printf("open file error!\n");
}
num = fwrite(str, 1, str_len, fp);
printf("num = %d\n", num);
fclose(fp);
/* <--- 方法2 */
}
/* 讀檔案測試函式 */
static void fread_demo()
{
FILE *fp; /* 檔案識別符號 */
char str[64]; /* 讀取的字串 */
int num; /* 讀出的長度 */
memset(str, 0, sizeof(str));
/* 方法1 ---> */
fp = fopen("file_1.txt", "r");
if(NULL == fp){
printf("open file error!\n");
return;
}
fseek(fp, 0, SEEK_SET); /* 定位到檔案開頭 */
if(1 != fread(str, 32, 1, fp)){ /* 讀取的長度小於檔案內容,返回1 */
printf("fread error!\n");
}
printf("1 -- %s\n", str);
memset(str, 0, sizeof(str));
fseek(fp, 0, SEEK_SET); /* 定位到檔案開頭 */
if(1 != fread(str, sizeof(str), 1, fp)){ /* 讀取的長度大於檔案內容,返回0 */
printf("fread error!\n"); /* 此處會列印 */
}
printf("2 -- %s\n", str);
fclose(fp);
/* <--- 方法1 > */
/* 方法2 ---> */
fp = fopen("file_2.txt", "r");
if(NULL == fp){
printf("open file error!\n");
return;
}
fseek(fp, 0, SEEK_SET); /* 定位到檔案開頭 */
num = fread(str, 1, sizeof(str), fp);
printf("3 -- %s\n", str);
printf("num = %d\n", num);
fclose(fp);
/* <--- 方法2 > */
}
int main(int argc, char **argv)
{
if(NULL == argv[1]){
printf("please input param!\n");
return;
}
if(0 == strcmp("fread", argv[1])){
fread_demo();
}else if(0 == strcmp("fwrite", argv[1])){
fwrite_demo();
}else{
printf("error param!\n");
}
}