天天看点

c语言读写文件fopen和fopen

当我们按照二进制方式往文件中写入数据,则将数据在内存中的存储形式原样输出到文件中

计算机文件基本上分为二种:二进制文件和 ASCII(也称纯文本文件),图形文件及文字处理程序等计算机程序都属于二进制文件。这些文件含有特殊的格式及计算机代码。ASCII 则是可以用任何文字处理程序阅读的简单文本文件。

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>


int main (void)
{
	
	//fwrite写入文件
	FILE * pfile=fopen("1.txt","wb");
	fwrite("我是你的大皇冠",1,strlen("我是你的大皇冠")+1,pfile);
	fseek(pfile,0,SEEK_SET);
	fwrite("哈哈",1,strlen("哈哈"),pfile);
	//fflush(pfile);
	fclose(pfile);


	//fread读取文件
	pfile=fopen("1.txt","rb");
	//文件指针移到到文件未获取文件长度
	fseek(pfile,0,SEEK_END);
	int len=ftell(pfile);
	//分配内存空间,文件指针移到到文件头开始读取
	char *szText=(char*)malloc(len+1);
	fseek(pfile,0,SEEK_SET); //rewind(pfile);
	fread(szText,1,len,pfile);
	printf("%s\n",szText);
	fclose(pfile);
	free(szText);

	//98341例子
	int a=98341;
	char szTemp[100]={0};
	int r=10; //10进制转换
	itoa(a,szTemp,r);
	

	return 0;
}
/*
2015年4月1日1:05:28
程序执行结果如下
哈哈你的大皇冠
请按任意键继续. . .
*/
           

unicode文本编码

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <wchar.h>
#include <tchar.h>
#include <windows.h>


int main(void)
{
	wchar_t str[100]=TEXT("我是你的大皇冠hello world!");
	size_t  strSize=NULL;
	FILE*   fileHandle=NULL;

	if ((fileHandle = _wfopen(TEXT("1.txt"),TEXT("wb,ccs=UNICODE"))) == NULL) // C4996
	{
		wprintf(L"_wfopen failed!\n");
		return(0);
	}

	strSize = _tcslen(str);
	if (fwrite(str, sizeof(wchar_t), strSize, fileHandle) != strSize)
	{
		wprintf(L"fwrite failed!\n");
	}

	if (fclose(fileHandle))
	{
		wprintf(L"fclose failed!\n");
	}
	return 0;
}