标签:
1. 写出文件
#include <stdio.h>
main()
{
FILE * f=fopen("data.txt","w");
if(f!=NULL) //quan xian
{
//fputc(‘A‘,f);
fputs("hello world",f);
fclose(f);
}
else
{
puts("File can not create");
puts("end");
}
2. 读取文件
#include <stdio.h>
#include <string.h>
main()
{
FILE * f=fopen("data.txt","r");
if(f!=NULL) //quan xian if(f) NULL==0
{
/* char ch=fgetc(f); */
/* printf("%c\n",ch); */
/* char buf[100]; */
/* fgets(buf,6,f); */
/* puts(buf); */
/* fclose(f); */
char buf[100];
memset(buf,0,100);
int i;
for(i=0;i<100;i++)
{
char ch=fgetc(f);
if(ch!=EOF)
buf[i]=ch;
else
break;
}
printf("%s\n",buf);
fclose(f);
}
else
{
puts("File can not read");
}
puts("end");
}
3. 格式化写出和读取文件
#include <stdio.h>
#include <string.h>
main()
{
/* FILE * f =fopen("data.txt","w"); */
/* if(f) */
/* { */
/* int i; */
/* for(i=0;i<100;i++) */
/* { */
/* fprintf(f,"Item %d\n",i); */
/* } */
/* fclose(f); */
/* }else{ */
/* printf("can not write to file"); */
/* } */
//read
FILE *f=fopen("data.txt","r");
if(f)
{
int a;
fscanf(f,"Item %d\n",&a);
fscanf(f,"Item %d\n",&a);
fscanf(f,"Item %d\n",&a);
printf("Num read is %d\n",a);
fclose(f);
}else{
puts("can not read file");
}
}
标签:
原文地址:http://www.cnblogs.com/htmlphp/p/4877292.html