文件操作单个字符的输入与读取
#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;
}