C++快速入门---文件IO(3)
argc与argv[]
在程序中,main函数有两个参数,整形变量argc和字符指针数组argv[]
argc:程序的参数数量,包括本身
argv[]的每个指针指向命令行的一个字符串,所以argv[0]指向字符串"copyFile.exe"。argv[1]指向字符串sourceFile,agrv[2]指向字符串destFile。
getc()函数一次从输入流(stdin)读取一个字符。
putc()函数把这个字符写入到输出流(stdout)。
复制文件的内容到另一个文件
C语言代码如下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *in, *out;
int ch;
if (argc != 3)
{
fprintf(stderr, "输入形式:copyFile 源文件名 目标文件名 \n");
exit(EXIT_FAILURE);
}
if ((in = fopen(argv[1], "rb")) == NULL)
{
fprintf(stderr, "打不开文件:%s\n", argv[1]);
exit(EXIT_FAILURE);
}
if((out = fopen(argv[2], "wb")) == NULL)
{
fprintf(stderr, "打不开文件:%s\n", argv[2]);
fclose(in);
exit(EXIT_FAILURE);
}
while ((ch = getc(in)) != EOF)
{
if(putc(ch, out) == EOF)
{
break;
}
}
if (ferror(in))
{
printf("读取文件 %s 失败! \n", argv[1]);
}
if (ferror(out))
{
printf("读取文件 %s 失败! \n", argv[2]);
}
printf("成功复制1个文件!\n");
fclose(in);
fclose(out);
return 0;
}
把文件的内容打印在屏幕上:
C++代码如下:(ifstream)
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in;
in.open("test.txt");
if(!in)
{
cerr << "打开文件失败" << endl;
return 0;
}
char x;
while (in >> x)//文件流到x里面去
{
cout << x;//再从x流到cout
}
cout << endl;
in.close();
return 0;
}
ofstream:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream out;
out.open("test.txt");
if (!out)
{
cerr << "打开文件失败!" << endl;
return 0;
}
for (int i = 0; i < 10; i++)
{
out << i;
}
return 0;
}
ifstream in(char *filename, int open_mode)
open_mode表示打开模式,其值用来定义以怎样的方式打开文件
常见的打开模式 ios::app:写入的所有数据将被追加到文件的末尾
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream out("test.txt", ios::app);
if(!out)
{
cerr << "文件打开失败!" << endl;
return 0;
}
for(int i = 10; i > 0; i--)
{
out << i;
}
out << endl;
out.close();
return 0;
}
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream fp("test.txt", ios::in | ios::out);//可读可写
if(!fp)
{
cerr << "打开文件失败!" << endl;
return 0;
}
fp << "hello world";
static char str[100];
fp.seekg(ios::beg); //使得文件指针指向文件头 ios::end则是文件尾
fp >> str;
cout << str <<endl;
fp.close();
return 0;
}