C中文件基本读写操作(单字符,多字符)

来源:互联网 发布:抠抠视频秀算法注册机 编辑:程序博客网 时间:2024/06/05 07:31
#include <iostream>
using namespace std;
void main(int argc,char *argv[]){
 //文件的写操作
 FILE* file = fopen("C:\\Users\\Administrator\\Desktop\\a.txt", "r");
 FILE* file2 = fopen("C:\\Users\\Administrator\\Desktop\\b.txt", "w");
  if (!file){
   cout << "打开失败" << endl;
  }else{
        cout << "打开成功" << endl;
  //读取一个字符串fgets(缓冲区,读取字符个数,文件指针)
   char* strBuf=new char[5]; //缓冲区 ;5:读取字符个数
   char* str=fgets(strBuf, 5, file);
   while (str!=NULL)
   {
    //cout << strBuf << endl;
    fputs(strBuf, file2);
    //memset(strBuf, 0, strlen(strBuf));
    str = fgets(strBuf, 5, file);
   }
}

  int n = fclose(file); //关闭
  if (n == 0)
  {
   cout << "正常关闭" << endl;
  }
  else{
   cout << "关闭出错" << endl;
  }
  fclose(file2);
  system("pause");
}


//读取一个字符
//进行操作 读取成功,返回字符的ASCII码。否怎返回EOF(-1)
//int ch = fgetc(file); //注意:ascii码要进行转换才能显示
/*char a = char(ch); cout <<a << endl;*/
//putchar(ch); //输出到屏幕

//  //1.一个字符一个字符的读取.和写入
//int n = fgetc(file);
//while (n != EOF) //一个字符一个字符循环读取
//{
// //写入到另外一个文件中去
// fputc(n, file2);
// putchar(n);
// n = fgetc(file);
//}



/*
stdin:标准输入流
stdout:标准输出流
stderr:错误提示流
*/
0 0
原创粉丝点击