C语言库函数---fopen fread fwrite

注意:这里fwrite的时候要使用strlen,不然会将位置字符写入文件中。

/*函数功能:
1、先向文件写入10行内容
2、读出第五行
3、删除第五行,然后打印所有*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    int i = 0;
    FILE *fp = NULL;
    char buff[20] = "hello the world!";
    char buff1[20] = {0};
        
    if((fp = fopen("a.txt","w+"))){
        for(i=0; i<10; i++){
            sprintf(buff1,"%s_%d\n",buff,i);
            fwrite(buff1,strlen(buff1),1,fp);
        }
        fclose(fp);
        fp = NULL;
    }
    
    if((fp = fopen("a.txt","r+"))){
        i=0;
        while(fgets(buff1,sizeof(buff1),fp)){
            i++;
            if(5 == i){
                printf("%s",buff1);
            }
        }
        fclose(fp);
        fp = NULL;
    }
}
发布了60 篇原创文章 · 获赞 6 · 访问量 6891

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/95607751