Linux编程-标准IO(2)

来源:互联网 发布:sql sum多个字段求和 编辑:程序博客网 时间:2024/06/04 11:55

简单的文件读写实例


#include "stdIOTest.h"
#include <stdio.h>
#include <string.h>
void ReadLog()
{
   FILE* pLog = fopen("./log.txt", "a+");
   if (NULL == pLog)
   {
  printf("open file failed\n");
  return;
   }

   printf("open file success\n");
  
   //单字节读取测试
  int iChar = fgetc(pLog);
  if (EOF == iChar)
  {
 printf("read file error\n");
 return;
  }


  //字节回送测试
  int iPut = ungetc(iChar, pLog);
  if (EOF == iPut)
  {
 printf("put char failed\n");
 return;
  }


  fseek(pLog, 0, SEEK_END);


  //单字符写测试
  iPut = fputc(iChar, pLog);
  if (EOF == iPut)
  {
 printf("put char failed\n");
 return;
  }


  char szbuf[100] = {"Test Std IO"};


  //行写测试
  fseek(pLog, 0, SEEK_END,);
  if (EOF == fputs(szbuf, pLog))
  {
 printf("put string failed");
 return;
  }
  printf("pet String: %s\n", szbuf);
  
  //读行测试
  fseek(pLog, 0, SEEK_SET);
  if (NULL == fgets(szbuf, 100, pLog))
  {
 printf("get string failed\n");
 return;
  }
  printf("Get String: %s\n", szbuf);


  //二进制写测试(可以用于直接写数据结构或二进制数据)
  fseek(pLog, 0, SEEK_END);
  char szbuf2[] = "WriteBin";
  if (fwrite(szbuf2, sizeof(char), strlen(szbuf2), pLog) != strlen(szbuf2))
  {
 printf("write bin failed\n");
 return;
  }


  printf("write bin :%s\n", szbuf2);


  //二进制写测试
  fseek(pLog, 0, SEEK_SET);
  if (fread(szbuf, sizeof(char), 100, pLog) == EOF)
  {
 printf("read bin failed\n");
 return;
  }


  printf("Read bin: %s\n", szbuf);

 fclose(pLog);

  return;
}

经过测试:


linux(ubuntu)下,存在如下情况:

一、特性标示说明:

r :支持读

w:支持写、创建文件,截断文件(清空内容)

a :支持写、支持自动在文件末尾添加

b :传说linux没有文本和二进制之分,不考究

r+:支持特性:读、写

w+:支持特性:读、写、创建文件、截断文件

a+:支持读、写、创建文件(不存在时),自动在文件末尾添加(不需要手动调用seek)

ra+、r+a 、rw+、r+w 等价r+,可见,第一个关键属性为有效字符,由man手册提供的说明中,没有出现两个字符的组合。可见,该特性的解析算法明显大致是:

(1) 查找“r、w、a”,找到一个则停止(由测试可知,特性中,最先出现的字符为有效特性,如rw = r)

(2.)找到再找“+”

(3)查找“b”

二、流的打开方式无法自由组合所有特性,可通过基本文件IO打开后再转化为流进行操作。

三、其他一下API     

void clearerr(FILE *stream);清除之前的错误码

int feof(FILE *stream);判断文件是否达到末尾

int ferror(FILE *stream); 获取错误码

int fileno(FILE *stream);将文件指针转化为文件描述符


0 0