当前位置:C++技术网 > 资讯 > fopen_s函数实例操作

fopen_s函数实例操作

更新时间:2015-11-21 00:45:46浏览次数:1+次

首先在编译器代码文件夹下保存一个txt文件,随便写入东西。我的VS13代码是放在F盘下的。

代码如下:


#include "stdio.h"
#include "windows.h"
#include "process.h"

FILE *stream, *stream2;

int main(void)
{
	errno_t err;
	char ch;
	// Open for read (will fail if file "in1.txt" does not exist)
	if ((err = fopen_s(&stream, "in1.txt", "r")) != 0)
	{
		printf("The file 'in1.txt' was not opened\n");
		//Sleep(3000);
	}
	else
	{
		printf("The file 'in1.txt' was opened\n");
		//Sleep(3000);
	}
	// Open for write 
	if ((err = fopen_s(&stream2, "data2.txt", "w+")) != 0)
	{
		printf("The file 'data2.txt' was not opened\n");
		//Sleep(3000);
	}
	else
	{
		printf("The file 'data2.txt' was opened\n");
		//Sleep(3000);
	}
	while ((ch = getc(stream)) != EOF)
	{
		//putchar(ch);
		fputc(ch, stream2);
	}
	fclose(stream);
	fclose(stream2);
	system("pause");
	return 0;
}
实现如下:


fopen_s函数还支持unicode编码,以及utf-8,utf-16等操作,待我研究透了,再分享。。。