Sian 发表于 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;
   
    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;
}运行结果:ip=192.168.1.254
port=8080Program ended with exit code: 0
页: [1]
查看完整版本: C语言中文件的基本读写操作