c++基础知识点-文件的创建,写入与读取(VS )

用C++创建文件并且进行对文件的写入和读取操作。

1)文件的创建:我用的软件是VS。
     FILE *fp1, *fp2;
	errno_t err;
	err = fopen_s(&fp1, "D:\\privacy_key.txt", "wb+");
	if (err == 0) printf(" the file was opened!\n");
	else printf("the file was not opened!\n");
这里用到了fopen_s()函数,因为更高级的编译环境中为了安全,如果用fopen()函数的话会出错,不信你试试。反正我是一直错。具体的fopen()和fopen_s()的区别,可以自己查查。参数里的wb+是可以根据你的需要改,wb+的意思是可以创建一个新文件并且往里面输入数据。
比如:创建/打开文件之后,往文件里输入字符串的操作。
 FILE *fp1, *fp2;
 char a[100];
 char b[100];
 errno_t err;
 err = fopen_s(&fp1, "D:\\privacy_key.txt", "wb+");
 if (err == 0) printf(" the file was opened!\n");
 else printf("the file was not opened!\n");
 printf("input a string\n");
 cin >> a;
 fputs(a, fp1);
 fclose(fp1);
这里就可以把a[]中的内容写进文件里。用到了fputs()函数,这个是直接向文件里输入字符串的操作,也有fputc()是向文件里输入单个字符的操作。具体的可以自行百度,我也都是刚用的时候才查的,没法细说,因为我也不会。
2)将刚刚创建的文件里的数据,读取出来。因为我刚刚关闭文件了,所以我重新打开这个文件,然后只读,就用“r".
        errno_t err2;
	err2 = fopen_s(&fp2, "D:\\privacy_key.txt", "r");
	if (err2 == 0) printf("the file was opened!\n");
	else printf("the file was not opened!\n");
	fgets(b, 5, fp2);
	cout << b << endl;
	fclose(fp2);

这里用到了fgets()函数,这个函数里面有个参数5,其实是你要读取的文件里的字符串的长度,可以自己定义,我只需要用到字符串的操作,所以,其他类型的不太会,不过应该是同理。每次我查文件的资料都特别多,找不到适合的。这个适合你吗?反正适合我

3)完整的实例代码:

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{
	FILE *fp1, *fp2;
	char a[100];
	char b[100];
	errno_t err;
	err = fopen_s(&fp1, "D:\\privacy_key.txt", "wb+");
	if (err == 0) printf(" the file was opened!\n");
	else printf("the file was not opened!\n");
	printf("input a string\n");
	cin >> a;
	fputs(a, fp1);
	fclose(fp1);
	errno_t err2;
	err2 = fopen_s(&fp2, "D:\\privacy_key.txt", "r");
	if (err2 == 0) printf("the file was opened!\n");
	else printf("the file was not opened!\n");
	fgets(b, 5, fp2);
	cout << b << endl;
	fclose(fp2);
	int u;
	cin >> u;
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_40129237/article/details/79709660