10 File Streams(文件流)

本文详细介绍了C语言中文件操作的基础知识,包括如何使用stdio.h中的函数打开、读取、写入和关闭文件。涵盖了不同文件模式的区别,如读、写、追加等,并提供了使用fprintf进行格式化输出,以及fread和fwrite进行字节读写的示例代码。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

1 The FILE * and opening files

1.All the file stream functions and types are defined in the header file stdio.h

1.1 Opening a file

FILE * stream;
FILE * fopen(const char *path, const char *mode);
FILE * stream = fopen("gonavy.txt", "w");

1.2 File Modes

mode描述
r读,stream在文件开头
r+读写,stream在文件头
w写,将文件内容删除,并写入,stream在文件头
w+读写,如果没有文件则创建,如果有则删除,stream在文件头
a追加,如果没有则创建,如果有则添加,stream在文件尾部
a+读追加,如果没有创建,stream读在开头,写在尾部

2 Format input/output from File Streams

2.1 Format Output with fprintf()

/*hello_fopen.c*/
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]){
  FILE * stream = fopen("helloworld.txt", "w");
  fprintf(stream, "Hello World!\n");
  fclose(stream);
}

3 Input/Output bytes from File Streams

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

3.1 Reading/Writing a single element

/*write_struct.c*/
#include <stdio.h>
#include <stdlib.h>


typedef struct{
  int left;
  int right;
} pair_t;

int main(int argc, char * argv[]){
  pair_t pair;
  pair.left = 10;
  pair.right = 20;
  FILE * stream = fopen("pair.dat","w");
  fwrite(&pair, sizeof(pair_t), 1, stream); # 结构体指针使用`&`
  close(stream);
}

3.2 Reading/Writing multiple elements

/*write_arraystruct.c*/
#include <stdio.h>
#include <stdlib.h>


typedef struct{
  int left;
  int right;
} pair_t;

int main(int argc, char * argv[]){
  pair_t pairs[10];
  int i;
  for( i=0; i < 10 ; i++){
    pairs[i].left = 10*i;
    pairs[i].right = 20*i;
  }
  FILE * stream = fopen("arraypair.dat","w");
  fwrite(pairs, sizeof(pair_t), 10, stream);
  close(stream);
}

3.3 Reading/Writing Raw Bytes

从一个文件读,写到另一个文件

/*mycp.c*/
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]){

  if(argc < 3){
    fprintf(stderr, "ERROR: %s src dest\n", argv[0]);
    return 1;
  }

  FILE * src, * dest;

  src  = fopen(argv[1], "r");
  dest = fopen(argv[2], "w");

  char data[1024];
  int n;

  while ( (n = fread(data, 1, 1024, src)) > 0){
    fwrite(data, 1, n, dest);
  }

  fclose(src);
  fclose(dest);

  return 0;
}

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值