读文件方法:
代码:
#include <stdio.h>
#include <fstream>
#include <iostream>
void CreateFile(const char * file_name);
void ReadFileUseC(const char * file_name);
void ReadFileUseCPP(const char * file_name);
int main(){
const char file_name[] = "test.txt";
CreateFile(file_name);
ReadFileUseC(file_name);
ReadFileUseCPP(file_name);
std::cout << "game over!" << std::endl;
return 0;
}
void CreateFile(const char * file_name){
printf("create file %s\n", file_name);
std::ofstream fout;
fout.open(file_name, std::ios::out);
fout << "hello,world" << std::endl;
fout << "i love china" << std::endl;
fout.close();
}
void ReadFileUseC(const char * file_name){
FILE * fp = fopen(file_name, "r");
char buff[256] = {0};
int index = 0;
while(1){
char c = fgetc(fp);
if(c == EOF){
break;
}
buff[index] = c;
index++;
}
fclose(fp);
printf("read file use c:\n%s", buff);
}
void ReadFileUseCPP(const char * file_name){
std::ifstream fin;
fin.open("test.txt", std::ios::in);
if(!fin.is_open()){
std::cout << "file open failed!" << std::endl;
return;
}
char c = '\0';
std::string file_content;
while(fin.get(c)){
file_content += c;
c = '\0';
}
fin.clear();
fin.close();
std::cout << "read file use c++:\n" << file_content.c_str();
}
输出:
[root@localhost test]# ls
main.cpp
[root@localhost test]# g++ -o demo main.cpp
[root@localhost test]# ls
demo main.cpp
[root@localhost test]# ./demo
create file test.txt
read file use c:
hello,world
i love china
read file use c++:
hello,world
i love china
game over!
[root@localhost test]#