C++-033-读写函数

C+±033-读写函数-2020-3-7

一、fputs与fgets函数

fgets的功能是在文件中读一行字符串。它有三个参数。

例如:
fgets(a,n,in);其中a是一个char型数组用于存放读取的字符串,n表示读取n~1个字符,in是文件读入指针。

fgets函数会在读入的数据末尾加上一个空字符以构成一个字符串。
fgets与gets的不同之处在于,fgets读取到换行符后不会将其省略,而gets读到换行符时会退出,并会将换行符略去。

fputs的功能是在文件中写入一行字符串。它有两个参数。

例如:
fputs(a,out);其中a是一个要输出的char型数组,out是文件输出指针。

fputs与puts的不同之处是fputs在打印时并不添加换行符。
如下:

//fgets and fputs
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
	FILE *in=fopen("i.txt","rb");//定义文件读入指针 
	FILE *out=fopen("0.txt","wb");//定义文件输出指针
	char a[9];
	fgets(a,10,in);
	fputs(a,out);
	return 0; 
} 

i.txt

1 2 3

0.txt//执行后

1 2 3

二、getc与putc函数

getc函数的功能是从文件中读出一个字符。

常用的判断文件是否读取结束的语句为:(ch=getc(fp)!=EOF。EOF为文件结束标志。文件也可以被理解为一种流,故当文件输入指针为in时,getc(in)就等同于getchar()了。

putc函数的功能是把字符ch写到文件中去。

如果文件输出指针为out,则putc(out)就等同于putchar()了。

如下:

//getc and putc
#include <cstdio>
int main()
{
	FILE*in=fopen("i.txt","rb");
	FILE*out=fopen("o.txt","wb");
	char c;
	c=getc(in);
	putc(c,out);
	return 0; 
} 

i.txt

3 2

0.txt//执行后

3

三、fgets与fputc函数

fgetc函数的功能是从fp的当前位置读取一个字符。
例如,fgetc(in);其中in是文件读入指针。
fputc函数的功能是将ch写入fp当前指定位置。
例如,fputs(ch,out);其中ch是要输出的字符,out是文件输出指针。

四、fscanf与fprintf函数

fscanf的功能是按照指定格式从文件中读入数据。
fprintf的功能是将格式化数据(这里的格式化即按照指定格式)写入文件中。

五、fin.get()

//fin.get()使用
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	int a,b,c,space;
	ifstream fin("in.txt");//输入新式:a b c
	ofstream fout("out.txt");//输出三个个位数的积到文件out.txt
	a=fin.get()-'0';
	space=fin.get();
	b=fin.get()-'0';
	space=fin.get();
	c=fin.get()-'0';
	fout<<a*b*c;
	fin.close();
	fout.close();
	return 0; 
} 

in.txt

2 2 3

out.txt//执行后

12

六、gets

//gets读字符串
#include<iostream>
#include <cstdio>
using namespace std;
int main()
{
	char a[100];
	gets(a);
	puts(a);
	return 0;
} 
Hello World
Hello World

--------------------------------
Process exited with return value 0
Press any key to continue . . .

七、getline

用getline(cin,sting)来读入一行包含空格符的字符串。

//getline读字符串
#include<iostream>
using namespace std;
int main()
{
	string str;
	getline(cin,str);
	cout<<str;
	return 0;
} 
Hello World
Hello World
--------------------------------
Process exited with return value 0
Press any key to continue . . .

八、cin.getline

用cin.getline(字符串指针,字符个数,结束符)。结束符默认是’\n’。

//cin.getline读字符串
#include<iostream>
using namespace std;
int main()
{
	char a[80];//注意与上一个程序数据类型的区别 
    cin.getline(a,80);
    cout<<a;
    return 0;
} 
Hello World
Hello World
--------------------------------
Process exited with return value 0
Press any key to continue . . .

九、getchar

//循环语句+getchar读字符串
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
	char c;
	while((c=getchar())!='\n')   //此句前面必要加括号,而且不能在freopen下使用
	cout<<c;
	return 0; 
} 
Hello World
Hello World
--------------------------------
Process exited with return value 0
Press any key to continue . . .
发布了91 篇原创文章 · 获赞 101 · 访问量 3309

猜你喜欢

转载自blog.csdn.net/weixin_41096569/article/details/104719365