C语言文件读写操作

文件操作单个字符的输入与读取 

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#if 0
int main()
{
	FILE *fp;		//定义文件指针
	char ch;
	if ((fp = fopen("D:\\file.txt", "a")) == NULL)
	{
		printf("Failure to open file.txt!\n");
		exit(0);
	}
	ch = getchar();
	while (ch != '\n')
	{
		fputc(ch, fp);
		ch = getchar();
	}
	fclose(fp);
	system("pause");
	return 0;
}
#endif

int main()
{
	FILE *fp;
	char ch;
	int i;
	if ((fp = fopen("D:\\file.bin", "wb")) == NULL)	//判断打开文件是否成功
	{
		printf("Failure to open file.bin\n");
		exit(0);
	}
	for (i = 0; i < 128; i++)	//向文健输入信息
	{
		fputc(i, fp);
	}
	fclose(fp);
	if ((fp = fopen("D:\\file.bin", "rb")) == NULL)
	{
		printf("Failure to open file.bin\n");
		exit(0);
	}
	while ((ch = fgetc(fp)) != EOF)	//判断位置指针是否到了文件末尾
	{
		if (isprint(ch))		//是否可打印,如果不能打印则打印ASCII值
		{
			printf("%c\n", ch);
		}
		else
			printf("%d\n", ch);
	}
	//while (!feof(fp))
	//{
	//	ch = fgetc(fp);	//读取字符
	//	putchar(ch);
	//}
	fclose(fp);

	system("pause");
	return 0;
}

文件字符串的读写操作

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>

int main()
{
	FILE *fp;
	char str[80];
	if ((fp = fopen("D:\\file.txt", "a")) == NULL)
	{
		printf("Failure to open file.txt\n");
		exit(0);
	}
	gets(str);
	fputs(str,fp);	//将字符串输入到文件中
	fclose(fp);
	if ((fp = fopen("D:\\file.txt", "r")) == NULL)
	{
		printf("Failure to open file.txt\n");
		exit(0);
	}
	fgets(str,10,fp);//从文件读取10-1个字符
	puts(str);//将字符显示到屏幕上
	fclose(fp);
	system("pause");
	return 0;
}    

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值