<pre name="code" class="cpp">ofstream类支持磁盘文件输出
//文件的输出
#include <fstream>
using namespace std;
void main() //程序从这里开始运行
{
ofstream SaveFile("cpp-home.txt");
SaveFile <<"Hello World, from www.cpp-home.com and Loobian!";
SaveFile<<endl;
SaveFile<<"the end"<<endl;
SaveFile.close();
}
//文件的读入
#include<iostream>
#include <fstream>
using namespace std;
void main() //程序从这里开始
{
ifstream OpenFile("cpp-home.txt");
char ch;
while(!OpenFile.eof())
{
OpenFile.get(ch);
cout<< ch;
}
OpenFile.close();
}
//C语言写入
#include <stdio.h>
int main()
{
FILE * fp =fp=fopen("cpp-home.txt","w");;
fprintf(fp,"%s\n","hello!");
fclose(fp);
return 0;
}
//c 文件的读取
/*
//cpp-home.txt
1 2 3 4
5 6 7 8
*/
#include "stdio.h"
int main()
{
FILE *fp;
int a[2][4]={0};
int i,j;
if((fp=fopen("cpp-home.txt","rt"))==NULL)
{
printf("cannot open file\n");
return 1;
}
for(i=0;i<2;i++)
{
for(j=0;j<4;j++)
fscanf(fp,"%d",&a[i][j]);
fscanf(fp,"\n");
}
for(i=0;i<2;i++)
{
for(j=0;j<4;j++)
printf("%d ",a[i][j]);
printf("\n");
}
fclose(fp);
return 0;
}
使用width控制输出宽度
cout.width(10);
cout.fill('*');
cout<<values[i]<<'\n';
使用setw指定宽度
cout<<setw(6)<<names[i]<<setw(10)<<values[i]<<endl;
C++ 文件操作
最新推荐文章于 2024-04-13 17:14:09 发布