//写文件两种方式(文本文件和二进制文件)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int readtxt(char *path){//传入文件地址
int ERRO_MSG = 0;
if (path==NULL)
{
ERRO_MSG = 1;
printf("文件路径不可以为空!path==NULL erro msg:%d\n ", ERRO_MSG);
return ERRO_MSG;
}
//定义文件指针(防止野指针)
FILE *pf=NULL;
//以文本方式读取使用r;以二进制方式读取使用rb
pf = fopen(path, "rb");
if (pf==NULL)
{
ERRO_MSG = 2;
printf("文件打开失败 !文件路径是 %s ,文件打开方式是rb pf==NULL erro msg:%d\n", path, ERRO_MSG);
return ERRO_MSG;
}
//定义一个字符
char ch;
int index = 1;
fread(&ch, 1, 1, pf);
//fread(缓冲数组地址,数组元素大小1个字节,每次读取1个元素,文件指针)
while (!feof(pf)){//没有读取到文件末尾就继续
printf("%c====%d\n", ch,index);
fread(&ch, 1, 1, pf);
index++;
}
//关闭文件指针
if (pf != NULL)
{
fclose(pf);
}
return ERRO_MSG;
}
void main(){
char str[50] = "我自狂刀向天笑,去留肝胆两昆仑!\n世人皆醉我独醒";
char strt2[11] = "1234567890";
//定义文本文件指针
FILE *pfw=NULL;
//定义二进制文件指针
FILE *pfb=NULL;
int num = 0;
//写一个文本文件
char pathw[40] = "E:/Look/w.txt";
char pathb[40] = "E:/Look/b.txt";
//一:文本模式
//打开文件
//w--写文件,如果没有,系统会创建一个,但是r--读文件,如果没有,文件指针就是NULL
pfw = fopen(pathw, "w");
if (pfw==NULL)
{
//文件打开失败
printf("文件打开失败\n");
return;
}
//文件打开成功
//将字符串写入txt中
//fwrite(数组首地址,数组元素大小1个字节,一共有50个元素,文件指针)
num = fwrite(str, 1, 50, pfw);
if (num != 50)
{
printf("文件读写出现IO错误 erro msg:%d\n");
}
if (pfw != NULL)
{
fclose(pfw);
}
//二:二进制模式
//打开文件
pfb = fopen(pathb, "wb");//区别,这是使用wb
if (pfb==NULL)
{
//文件打开失败
printf("文件打开失败\n");
return;
}
//文件打开成功
//将字符串写入txt中
num = fwrite(strt2, 1, 11, pfb);
//关闭文件指针
if (pfb != NULL)
{
fclose(pfb);
}
//fwrite(数组首地址,数组元素大小1个字节,一共有50个元素,文件指针)
printf("\n打印出文件\n");
readtxt(pathb);
system("pause");
}
![]()