C++读写文件问题
来源:百度知道 编辑:UC知道 时间:2024/06/09 02:19:16
想要读一个txt文件的内容,写入另外一个txt文件中,写的文件最后两位是原文件中不存在的,程序如下,劳烦高手帮忙看看!!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include "fstream.h"
int main(int argc, char* argv[])
{
FILE *fp;
FILE *fp1;
int temp = 0;
int buffer1[10];
if((fp1 = fopen("D:\\test_speech\\lmy\\lmy.txt", "rt")) == 0)
{
printf("open failed!\n");
exit(1);
}
if((fp = fopen("D:\\test_speech\\com\\lmy-lmy^0.5.txt", "at")) == 0)
{
printf("open failed!\n");
exit(1);
}
do {
fread(buffer1, 1, 10, fp1);
fwrite(buffer1, 1, 10, fp);
temp = feof(fp1);
printf("%d\t", temp);
}while (!temp);
fclose(fp1)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include "fstream.h"
int main(int argc, char* argv[])
{
FILE *fp;
FILE *fp1;
int temp = 0;
int buffer1[10];
if((fp1 = fopen("D:\\test_speech\\lmy\\lmy.txt", "rt")) == 0)
{
printf("open failed!\n");
exit(1);
}
if((fp = fopen("D:\\test_speech\\com\\lmy-lmy^0.5.txt", "at")) == 0)
{
printf("open failed!\n");
exit(1);
}
do {
fread(buffer1, 1, 10, fp1);
fwrite(buffer1, 1, 10, fp);
temp = feof(fp1);
printf("%d\t", temp);
}while (!temp);
fclose(fp1)
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream ifstrm("in.txt");
ofstream ofstrm("out.txt");
if(!ifstrm || ! ofstrm)
throw;
cout << "in:\n" << ifstrm.rdbuf() << endl;
ifstrm.seekg(-1, ios_base::end);
ios::pos_type end = ifstrm.tellg();
ifstrm.seekg(ios_base::beg);
char c;
cout << "\nout:\n";
while(ifstrm.get(c) && ifstrm.tellg() != end)
{
cout << c;
ofstrm << c;
}
}
测试:
in:
I have a pretty cat
and her name is kitty
out:
I have a pretty cat
and her name is kit
应该是你读到文件最后时不一定能读出那么10个字节出来所以buffer1中存放的是上次读出来这次没有被覆盖的内容。
还有为了方便调试最好把buffer1设为char型这样你就可以随时了解你读出了哪些数据。
对你的程序我改了下,运行完全正确已经实现你要求的功能,修改的地方做了注释希望对你有帮助: