从一个txt读取内容写到另一个txt遇到的问题
代码如下
char chch[200];
int icout = 0;
char *strIndex;
ifstream fin("a.txt");
do
{
fin.getline(chch, 200, '\n');
icout = icout + 1;
if (0 == icout - 3)
{
cout << chch << endl << icout << endl;
strIndex = chch;
}
//cout << ch << endl;
} while (fin != NULL);
cout << endl;
fin.close();
FILE *pFile;
pFile = fopen("abcd.txt", "wb");
fwrite(strIndex, sizeof(strIndex), 1, pFile);
fclose(pFile);
a。txt中内容如下
1.xml
2.xml
3.xml
4.xml
我想读取a。txt的第三行3.xml 然后写到另一个abcd。txt
为什么写进去以后出现乱码
[解决办法]
你的strIndex 没回到数组最开始.指针越界了.
[解决办法]
char chch[200];int icout = 0;char *strIndex;ifstream fin("a.txt");do {fin.getline(chch, 200, '\n');icout = icout + 1;if (0 == icout - 3){cout << chch << endl << icout << endl;strIndex = chch;break;}// cout << ch << endl;} while (fin != NULL);fin.close();cout <<strIndex<< endl;FILE *pFile;pFile = fopen("abcd.txt", "wb");fwrite(strIndex, 1, strlen(strIndex), pFile);fclose(pFile);
[解决办法]
char chch[200]={0}; int icout = 0; char *strIndex; ifstream fin("a.txt"); do { fin.getline(chch, 200, '\n'); icout++; if (icout==3) { cout << chch <<" "<< icout << endl; strIndex = chch; break; //拿到3.xml 跳出 } } while (fin != NULL); cout << endl; fin.close(); FILE *pFile; pFile = fopen("abcd.txt", "w"); //文本模式打开 fputs(strIndex,pFile); fclose(pFile);
[解决办法]
fwrite(strIndex, sizeof(strIndex), 1, pFile);
就个指针的大小