C++怎么从把一个txt文本内容完全读到一个string中

2024-11-30 15:38:26
推荐回答(2个)
回答1:

char *str;//文件路径

FILE* fp = fopen(str,"rb");

if( fp == NULL )
{
return false;
}

fseek(fp,0,SEEK_END);
long dwFileSize = ftell(fp);
rewind(fp);

char* pchBuf = new char[dwFileSize];

memset( pchBuf,0,dwFileSize);
char* pchSet = pchBuf;

while( !feof(fp) )
{
int nReadLen = fread( pchBuf,1,1024,fp);

pchBuf += nReadLen;

}

fclose(fp);
pchBuf = pchSet;

delete pchBuf;

请参考

回答2:

ifstream in(d:\1.txt);
string s1,s2;
while(getline(in,s1))
{
s2+=s1;
s2 += '\n';
}
你试下这个可以不?