文件操作(二進制讀寫)


/***
a.txt
***/
this is a word
helloworld

/***
file.c
***/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    FILE *p = fopen("./a.txt","r");
    while(!feof(p))
    {
        char buf[100] = {0};
        fscanf(p,"%s",buf);
        printf("%s\n",buf);
    }
    fclose(p);
    return 0;
}

fscanf()函數和scanf函數用法一樣。fscanf是從一個文件中讀取字符串,scanf是從鍵盤讀取字符串。(遇到空格就停止)

/***
a.txt
***/
23 + 45 = 
35 + 63 =
34 + 45 =

/***
file1.txt
***/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    int a,b;
    FILE *p = fopen("./a.txt","r");
    while(!feof(p))
    {
        char buf[100] = {0};
        //fgets(buf,"%s",p);
        //fscanf(p,"%s",buf);
        fscanf(p,"%d + %d = ",&a,&b);
        printf("a = %d , b = %d\n",a,b);
        //printf("%s\n",buf);
    }
    fclose(p);
    return 0;
}

/***
fprintf.c
***/
#include<stdio.h>
#include<string.h>

int main()
{
    FILE *p = fopen("./b.txt","w");
    char buf[100] = "hello world";
    fprintf(p,"%s",buf);
    fclose(p);
    return 0;
} 

fread()函數和fwrite()函數:操作文本文件和二進制文件

fopen()函數只能讀文本文件

/***
fread.c
***/

#include<stdio.h>
int main()
{
    FILE *p = fopen("./a.txt","rb");
    char buf[100] = {0};
fread(buf,sizeof(char),1,p); //第一個參數是緩沖區,第二個參數是讀取字節大小,第三個 //參數表示讀取字節個數,第四個參數表示文件指針
    printf("buf = %s\n",buf);
    fclose(p);
    return 0;
}

/***
fread1.c
***/

#include<stdio.h>
int main()
{
    FILE *p = fopen("./a.txt","rb");

    while(!feof(p))
    {
        char buf[20] = {0};
        fread(buf,sizeof(char),sizeof(buf),p);
        printf("buf = %s\n",buf);
    }
    fclose(p);
    return 0;
}

fread()函數有返回值,返回的是size_t類型,unsigned int ==》 %u

/***
fread.c
***/
#include<stdio.h>
int main()
{
    FILE *p = fopen("./c.txt","rb");
    char buf[1024] = {0};
    size_t res = fread(buf,sizeof(char),sizeof(buf),p);
    printf("res = %u\n",res);
/*
    while(!feof(p))
    {
        char buf[20] = {0};
        fread(buf,sizeof(char),sizeof(buf),p);
        printf("buf = %s\n",buf);
    }
*/
    fclose(p);
    return 0;
}

/***
c.txt
***/
asd

運行結果:res = 4(文件結尾有一個換行字符‘\n’?);

 

size_t res = fread(buf,sizeof(int),sizeof(buf),p);

運行結果:res = 1;

 

以上程序的運行結果和windos環境下讀文本文件的結果會出現差異。

/***
fwrite.c
***/
#include<stdio.h>

int main()
{
    FILE *p = fopen("./d.txt","wb");
    char buf[1024] = {0};
    buf[0] = 'a';
    buf[1] = 'b';
    buf[2] = 'c';
    fwrite(buf,sizeof(char),sizeof(buf),p);
    fclose(p);
    return 0;
}

運行結果:abc

文件大小是1K(buf)數組大小,文件后面全是0。

/***
fwrite.c
***/
#include<stdio.h>

int main()
{
    FILE *p = fopen("./d.txt","w");
    int a = 0x12345678;
    fwrite(&a,sizeof(char),4,p);
    fclose(p);
    return 0;
}

 


免責聲明!

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



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