BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #18353同步于 2009/1/5
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

read函数的使用

tsunami
2009/1/5镜像同步15 回复
想把a.txt文件中的字符串"i love bupt"读到程序的 char*pa=new char[100];的字符串指针当中去, ifile.read( (char*)pa, ); 这里read函数第二个参数即读入字节长度怎么写呢? 如何才能知道文件中的字符串长度呢? 或者有什么其他好的方法呢,欢迎大牛赐教哈!
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
yegle机器人#1 · 2009/1/5
即使你知道又怎么样呢?不还是用固定大小的数组存么? 【 在 tsunami (风之子) 的大作中提到: 】 : 想把a.txt文件中的字符串"i love bupt"读到程序的 : char*pa=new char[100];的字符串指针当中去, : ifile.read( (char*)pa, ); : ...................
tsunami机器人#2 · 2009/1/5
知道了具体长度,我就可以准确设置第二个参数了,否则设置为常量如100,读入后在i love bupt后面还显示很多乱码~
yegle机器人#3 · 2009/1/5
c++?用string然后用getline吧 或者一个字节一个字节读然后判断是否是换行…我只会这个办法… 【 在 tsunami (风之子) 的大作中提到: 】 : 知道了具体长度,我就可以准确设置第二个参数了,否则设置为常量如100,读入后在i love bupt后面还显示很多乱码~
hg机器人#4 · 2009/1/5
CString read_file(CString filename) { CFile file; CString rstr; char buf[1000];//读1K int length; if(!file.Open(filename,CFile::modeRead)) { return ""; } while((length=file.Read(buf,1000))>0) { buf[length]=0; rstr+=buf; } file.Close(); return rstr; }
ericyosho机器人#5 · 2009/1/5
那个值,本来就是给你希望读入的最大长度的。 那后面是乱码有什么关系么?反正有用的信息和无用的信息之间有'\0'。 一点关系也没有啊。
white127机器人#6 · 2009/1/6
fscanf?
tsunami机器人#7 · 2009/1/6
不过怎么才能只显示有用信息呢? 现在我的源代码是这样的: void main() { char*pa=new char[100]; ifstream ifile("Encode_string.txt"); if(ifile) { ifile.read( (char*)pa,100); } cout<<pa; } 运行结果见附件! 【 在 ericyosho 的大作中提到: 】 : 那个值,本来就是给你希望读入的最大长度的。 : 那后面是乱码有什么关系么?反正有用的信息和无用的信息之间有'\0'。 : 一点关系也没有啊。 附件(744.1KB) 1.bmp
famousz机器人#8 · 2009/1/6
// basic_ifstream_class.cpp // compile with: /EHsc #include <fstream> #include <iostream> using namespace std; int main(int argc, char **argv) { ifstream ifs("basic_ifstream_class.txt"); if (!ifs.bad()) { // Dump the contents of the file to cout. cout << ifs.rdbuf(); ifs.close(); } } from MSDN
famousz机器人#9 · 2009/1/6
read: Reads a specified number of characters from the stream and stores them in an array. Deprecated. Use basic_istream::_Read_s instead.