【总结】C/C++输入输出不完全总结(待续)

1. C风格 FILE*, fwrite, fread

语法为:

  1. #include<cstdio>或者#include<stdio.h>
  2. FILE* fd = fopen(<文件名字符串>,"<参数>");//文件名字符串的类型一般是字符串常量或者字符串数组 const char*
  3. //写到文件 从起始地址begin起,写入number个size字节的数据
  4. fwrite(<要写进文件的内存起始地址begin>,<单元大小size>,<单元个数number>,<文件对象fileobj>);
  5. //读文件
  6. fread();
  7. fclose();
  8. fgetc();读字符
  9. fputc(); 写字符
  10. fputs(); 写字符串

实例代码

  1. #include<cstdio>或者#include<stdio.h>
  2. voidDataset::dumpData(constchar savefile[],int numDatam double* data,double* label){
  3. FILE* fd = fopen(savefile,"wb+");
  4. if(fd = NULL){
  5. printf("file doesn't exist: %s\n", savefile);
  6. exit(1);
  7. }
  8. fwrite(&numData,sizeof(int),1, fd);
  9. fwrite(&numFeature,sizeof(int),1, fd);
  10. if(label != NULL){
  11. fwrite(&numLabel,sizeof(int),1, fd);
  12. }
  13. fwrite(data,sizeof(double), numData*numFeature, fd);
  14. if(label != NULL){
  15. fwrite(label,sizeof(double), numData*numLabel, fd);
  16. }
  17. fclose(fd);
  18. }

相关知识:
FILE不是关键字,而是一个自定义数据类型,用于变量声明,它的定义在stdio.h中,具体定义如下:

  1. typedefstruct
  2. {
  3. unsignedchar*curp;/* Current active pointer */
  4. unsignedchar*buffer;/* Data transfer buffer */
  5. int level;/* fill/empty level of buffer */
  6. int bsize;/* Buffer size */
  7. unsignedshort istemp;/* Temporary file indicator */
  8. unsignedshort flags;/* file status flags */
  9. wchar_t hold;/* Ungetc char if no buffer */
  10. char fd;/* file descriptor */
  11. unsignedchar token;/* Used for validity checking */
  12. } FILE;

函数原型

  1. size_t fread(void* buffer,size_t size,size_t count, FILE* stream);
strtok_r

2. C风格 fscanf(), getc(), fgets(), sscanf()

语法:
实例代码:
svmdataset

3. **C风格 readline(FILE* INPUT), fgets(), strrchr, **

语法:
实例代码:
svm.cpp

4. C++风格 fstream, is_open(), read(), seekg(), tellg()

语法:
实例代码:

  1. voidMNISTDataSet::loadData(constchar* filepath){
  2. fstream infile(filepath, ios::in|ios::binary);
  3. if(!infile.is_open()){
  4. cout <<"cannot open the file"<< endl;
  5. return;
  6. }
  7. }

相关知识:

5. C++风格 getline(), istringstream, >>

语法:
实例代码:

  1. voidDataReader::read(vector<fv_type>& allfv, vector<label_type>& labels){
  2. string line;
  3. allfv.reserve(2400000);
  4. labels.reserve(2400000);
  5. allfv.clear();
  6. labels.clear();
  7. int counter =0;
  8. }

相关知识:

 

posted @ 2015-09-01 11:15  _扬帆起航  阅读(298)  评论(0编辑  收藏  举报