年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1878|回复: 0

C语言中文件的基本读写操作

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2016-6-7 11:50:37 | 显示全部楼层 |阅读模式
    [C] 纯文本查看 复制代码
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int write()
    {
        // 文件路径
        const char *filepath = "/Users/yusian/Desktop/hello.txt";
        // 定义文件指针
        FILE *fp = fopen(filepath, "wb");
        if (fp == NULL){
            printf("Faild to open file!\n");
            return -1;
        }
        
        {   // code...
            char ip[] = "192.168.1.254";
            int port = 8080;
            
            fprintf(fp, "ip=%s\n", ip);
            fprintf(fp, "port=%d", port);
        }
        // end
        fclose(fp);
        return 0;
    }
    
    int load()
    {
        const char *filepath = "/Users/yusian/Desktop/hello.txt";
        FILE *fp = fopen(filepath, "rw");
        if (fp == NULL){
            printf("Faild to open file!\n");
            return -1;
        }
        // code...
        
        char bf[512];
        
        while(!feof(fp)){
            // 按行读取
            char *line = fgets(bf, 512, fp);
            if(line){
                printf("%s", line);
            }
        }
        
        // end
        fclose(fp);
        return 0;
    }
    
    int main()
    {
        write();
        load();
        return 0;
    }
    运行结果:
    [C] 纯文本查看 复制代码
    ip=192.168.1.254
    port=8080Program ended with exit code: 0

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-3-29 07:49 , Processed in 0.046863 second(s), 22 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表