首先打开VC++6.0。
选择文件,新建。
选择C++ source file 新建一个空白文档。
先声明头文件#include <stdio.h>。
写上主函数
void main
主要代码
FILE *infile,*outfile,*otherfile
char input
char inputs[10]
int i=0
infile = fopen("d:\\infile.txt","r+")//用fopen函数打开文件
outfile = fopen("d:\\outfile.txt","a+")//用fopen函数打开文件
if ( !infile )
printf("open infile failed....\n")
if ( !outfile)
printf("open outfile failed...\n")
printf("*********************************************\n")
printf("** This program is to show file operation! **\n")
printf("** The input file is: **\n")
printf("** d:\\infile.txt **\n")
printf("** The contents in this file is: **\n")
printf("\n")
for()
{
input = fgetc(infile)//死循环读出文件内容
printf("%c",input)
putc(input,outfile)//写入内容
i++
if(input == '\n' || input == EOF)
break
}
fclose(infile)
fclose(outfile)
scanf("%d",i)
运行结果
1、首先输入下方的代码
#include <stdio.h>
int main()
{
//下面是写数据,将数字0~9写入到data.txt文件中
FILE *fpWrite=fopen("data.txt","w")
if(fpWrite==NULL)
{
return 0
}
for(int i=0i<10i++)
fprintf(fpWrite,"%d ",i)
fclose(fpWrite)
//下面是读数据,将读到的数据存到数组a[10]中,并且打印到控制台上
int a[10]={0}
FILE *fpRead=fopen("data.txt","r")
if(fpRead==NULL)
{
return 0
}
for(int i=0i<10i++)
{
fscanf(fpRead,"%d ",&a[i])
printf("%d ",a[i])
}
getchar()//等待
return 1
}
2、面是写入到txt后的截图:
3、下面是读取文件后打印数据到控制台的截图。
C++的文本文件写入// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>// for file I/O
int main()
{
using namespace std
char automobile[50]
int year
double a_price
double d_price
ofstream outFile // create object for output
outFile.open("carinfo.txt") // associate with a file
cout <<"Enter the make and model of automobile: "
cin.getline(automobile, 50)
cout <<"Enter the model year: "
cin >>year
cout <<"Enter the original asking price: "
cin >>a_price
d_price = 0.913 * a_price
// display information on screen with cout
cout <<fixed
cout.precision(2)
cout.setf(ios_base::showpoint)
cout <<"Make and model: " <<automobile <<endl
cout <<"Year: " <<year <<endl
cout <<"Was asking $" <<a_price <<endl
cout <<"Now asking $" <<d_price <<endl
// now do exact same things using outFile instead of cout
outFile <<fixed
outFile.precision(2)
outFile.setf(ios_base::showpoint)
outFile <<"Make and model: " <<automobile <<endl
outFile <<"Year: " <<year <<endl
outFile <<"Was asking $" <<a_price <<endl
outFile <<"Now asking $" <<d_price <<endl
outFile.close() // done with file
return 0
}