【发布时间】:2014-06-06 11:03:06
【问题描述】:
我写了这段代码。在这个程序中,我读取一个文件,然后将部分文件倒入 char* temp 中。最后将char *temp写入文件。我有问题。 当我在文件中写入临时文件时,只写了 4 个字符。我该怎么办?
fstream file;
file.open("mary.txt",ios::in);
file.seekg(-1,ios::end);
int pos=file.tellg();
char ch;
char c;
int i=0;
char * temp=new char[100];
file.seekg(0,ios::beg);
while(pos >=0)
{
file.read(&ch,sizeof(char));
if(ch=='a'||ch=='o'||ch=='u'||ch=='e'||ch=='i'||ch=='A'||ch=='O'||ch=='U'||ch=='E'||ch=='I')
{
pos--;
continue;
}
else if(ch>='a' && ch<='z')
{
c=ch-32;
temp[i]=c;
i++;
}
else
{
temp[i]=ch;
i++;
}
pos--;
}
temp[i]=NULL;
cout<<temp<<endl;
cout<<" sizeof temp:"<<sizeof(temp)<<endl;//out put is 4 while temp has longer size!! why?
fstream f("test.txt",ios::trunc);
f.write(temp,sizeof(temp));//if the file contains "abcdeifjle" only written "abcd"
【问题讨论】:
-
使用
strlen(temp),而不是sizeof(temp) -
sizeof(temp)为您提供指针变量的大小,对于您当前的环境(32 位),它实际上似乎是 4 个字节。 -
使用 strlen 代替 sizeof 并且不要忘记在最后调用 flush 和 close 方法。
-
@SudhakarB: 无需显式刷新和关闭
fstream;析构函数会解决这个问题。不过,您确实需要delete [] temp(或者,更好的是,改用 C++ 字符串)。 -
@MikeSeymour,是的,但这是一个很好的做法(看看这个stackoverflow.com/questions/5036878/…)