1. 程式人生 > >C語言強化——文件

C語言強化——文件

open int utc fread erro stdin 錯誤 ets hang

文件操作

  • fopen與fclose
  • fread與fwrite
  • fseek
  • fputs與fgets
  • fscanf與fprintf
fopen與fclose
#include<stdio.h>

int main() {
    FILE *fp;
    char c;
    fp = fopen("1.txt", "r");
    if (NULL == fp) {
        perror("fopen");   //perror()函數打印str(字符串)和一個相應的執行定義的錯誤消息到全局變量errno中. 
    }
    while ((c = fgetc(fp)) != EOF) {
        putchar(c);
    }
    fclose(fp);
    return 0;
}
fread與fwrite

技術分享圖片

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE *fp;
    char buf[128] = { 0 };
    int i = 0x12340a78;
    int ret;
    fp = fopen("1.txt", "rb+");
    if (NULL == fp)
    {
        perror("fopen");
    }
    //打印文件內容
    //while(memset(buf,0,sizeof(buf)),(ret=fread(buf,sizeof(char),sizeof(buf)-1,fp))>0)
    //{
    //  printf("%s",buf);
    //}

    //寫入文件
    strcpy(buf, "hello\nworld");
    fwrite(buf, sizeof(char), strlen(buf), fp);

    //fwrite的返回值是寫的對象的數量
    /*ret=fwrite(&i,sizeof(int),1,fp);
    i=0;*/
    /*fread(&i,sizeof(int),1,fp);
    printf("i=%x\n",i);*/
    fclose(fp);

    return 0;
}
fseek

技術分享圖片

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE *fp;
    int ret;
    char buf[128]={0};
    fp=fopen("1.txt","r+");
    if(NULL==fp)
    {
        perror("fopen");
    }
    ret=fseek(fp,6,SEEK_SET);   //成功返回0,失敗返回非零
    ret=fread(buf,sizeof(char),2,fp);
    printf("buf=%s\n",buf);
    fseek(fp,0,SEEK_CUR);
    ret=fwrite("you are how",sizeof(char),11,fp);
    fclose(fp);
    return 0;
}
fputs與fgets

技術分享圖片

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE *fp;
    int ret;
    char buf[128];
    fp=fopen("1.txt","r+");
    if(NULL==fp)
    {
        perror("fopen");
    }
    while(fgets(buf,sizeof(buf),stdin))
    {
        fputs(buf,fp);   //等價於printf("%s\n",buf);
    }
    return 0;
}
fscanf與fprintf

技術分享圖片

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
    int num;
    char name[20];
    float score;
}Stu;
int main()
{
    int num=20;
    float score=98.5;
    Stu sArr[3]={1001,"zhangfei",66.5,1007,"liubei",96.5,1005,"guanyu",97.3};
    int ret,i;
    FILE *fp=fopen("file.txt","r+");
    if(NULL==fp)
    {
        perror("fopen");
    }
    //ret=fprintf(fp,"%d %5.2f\n",num,score);
    //num=0;
    //score=0;
    //ret=fscanf(fp,"%d%f",&num,&score);
    for(i=0;i<3;i++)
    {
        ret=fprintf(fp,"%d %s %5.2f\n",sArr[i].num,sArr[i].name,sArr[i].score);
    }
    fseek(fp,0,SEEK_SET);
    memset(sArr,0,sizeof(sArr));
    for(i=0;i<3;i++)
    {
        ret=fscanf(fp,"%d%s%f",&sArr[i].num,sArr[i].name,&sArr[i].score);
    }
    fclose(fp);
    return 0;
}

C語言強化——文件