标准IO函数练习

一、使用fgets实现计算一个文件有几行

#include <head.h>
int main(int argc, const char *argv[])
{
    FILE *fp =fopen("1.txt","r");
    if(NULL == fp)
    {
        ERR_MSG("fopen");
        return -1;
    }
    char str[10]="";
    int count=0;
    while(1)
    {
        if(fgets(str,sizeof(str),fp) == NULL)
            break;
        count++;
    }
    printf("有%d行\n",count);
    fclose(fp);

    return 0;
}

二、用fread和fwrite实现文件拷贝

#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
    FILE *fp = fopen("1.txt","r");
    if(NULL == fp)
    {
        fprintf(stderr,"__%d__",__LINE__);
        perror("fopen");
        return -1;
    }   
    FILE *fp_w = fopen("2.txt","w");
    if(NULL == fp_w)
    {   
        fprintf(stderr,"__%d__",__LINE__);
        perror("fopen");
        return -1;
    }   
    char str[128];
    while(1)
    {
        memset(str,0,sizeof(str));
        res = fread(str,1,sizeof(str),fp);
        if(res == 0)
            break;
        fwrite(str,1,res,fp_w);
    }
    fclose(fp);
    fclose(fp_w);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_53478812/article/details/131945897