标准IO函数练习

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

#include 
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 
#include 
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;
}

你可能感兴趣的:(IO进程线程练习,#,IO练习(7月26),开发语言,标准IO函数)