如何用c++中的read函数读取文件中的数据??? 10
展开全部
Read函数定义
通过read函数将文件中的数据按照一定的长度读取出来并且存放在新的数组中。用于从文件中读取数据。
函数原型istream& read (char* s, streamsize n);
参数char* s取出数据的流向的char类型数组指针,streamsize n表示数组的长度
参看官方链接http://www.cplusplus.com/reference/istream/istream/read/?kw=read
Read函数使用例子
#include <iostream> // std::cout
#include <fstream> // std::ifstream
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
std::cout << "Reading " << length << " characters... ";
// read data as a block:
is.read (buffer,length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
// ...buffer contains the entire file...
delete[] buffer;
}
return 0;
}
通过read函数将文件中的数据按照一定的长度读取出来并且存放在新的数组中。用于从文件中读取数据。
函数原型istream& read (char* s, streamsize n);
参数char* s取出数据的流向的char类型数组指针,streamsize n表示数组的长度
参看官方链接http://www.cplusplus.com/reference/istream/istream/read/?kw=read
Read函数使用例子
#include <iostream> // std::cout
#include <fstream> // std::ifstream
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
std::cout << "Reading " << length << " characters... ";
// read data as a block:
is.read (buffer,length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
// ...buffer contains the entire file...
delete[] buffer;
}
return 0;
}
展开全部
先用int fd=open(“filepath”)打开文件;获得文件描述符
然后read(fd,buf,sizeof(buf));
然后read(fd,buf,sizeof(buf));
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
#include <fstream>
istream& read( char* buffer, streamsize num );
ifstream fin( "/tmp/data.txt" );
ofstream fout( "/tmp/results.txt", ios::app );
while( fin >> temp )
fout << temp + 2 << endl;
fin.close();
fout.close();
楼上是Linux的
istream& read( char* buffer, streamsize num );
ifstream fin( "/tmp/data.txt" );
ofstream fout( "/tmp/results.txt", ios::app );
while( fin >> temp )
fout << temp + 2 << endl;
fin.close();
fout.close();
楼上是Linux的
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询