How to Read files with C++?

This page is tips for how to read files with C++.

Over view of Byte Data

Create File read write close advantage drawback clear file that already exist
WinAPI CreateFile ReadFile WriteFile CloseHandle(HANDLE) TRUNCATE_EXISTING
c++ STL ifstream.open("full path of filw",ios::in |ios::binary);  ifstream ofstream filehandle名.close() ios::trunc
c FILE read,fread write filehandle.close() 
MFCのCFile stdFile.Open(_T("path"),read or write)) Read() Write() filehandle.Close(); modeCreate

How to read binary data?

fstream ifs;
ifs.open("input.data",ios::binary);

ifs.readsome is useful. If you find a certain bit, you can stop there.

How to read text file ?

create file read each line write each line close advantage drawback
MFCのCStdioFile stdFile.Open(_T("パス"),read or write)) ReadString() WriteString() .Close(); Multibyte string writing needs setllcale()
c fopen() fgets() fclose() It is available only char,not for string
c++ open() getline() close() It is available only char,not for string

reading each line

this code is reading text file each lines,and print.
getline()'s arg is char. it is annoying. for the matter of worse, it is no end with '\0' terminator.

#include <fstream> 
char line[255];
     ifstream ifs;
     int count=0;
    ifs.open(FILENAME, ios::in); //open a file in read only mode
     while( !ifs.eof() ){
        ifs.getline(line, sizeof(line));//read one line
        printf("[%03d] %s\n", count, line);
        count++;
    }
 
    ifs.close();

The way read text file using operator "»".
In this way,you can read data into string.
#include <string>
#include <fstream>
#include <iostream>
ifstream ifs;
string str;
ifs >> str;

In this way, blank space ' ' are interpreted as a separator.
if you want to set read type, try

setf(ios::dec,ios::basefield);

read chunk of data at once

It is fast that reading chars with fread()

FILE* fp;
const int readnum=100;//number of chars you want to read. '\n' is also taken into count.
char buf[readnum+1];//If you read by fread(), "\0" were not added automatically,so you have to add '\n' space(+1).
fp=fopen("data.txt","r");
fread(buf,sizeof(char),readnum,fp);
buf[readnum]='\0';
printf("%s\n",buf);//
fclose(fp);

Read each char

use fgetc(),getc()

en.gif en
ja.gif ja


edit
サポートサイト Wikidot.com