C语言读写文件(转)
// 读一个字符#include "stdio.h"
#include "string.h"
main()
{
FILE *fp;
char c;
if((fp=fopen("s.c","r"))==NULL)
{
printf("File can not open!");
getch();
exit(0);
}
while(!feof(fp))
{
c=fgetc(fp);
putchar(c);
}
fclose(fp);
getch();
system("pause");
}
// 写一个字符
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
main()
{
FILE *fp;
char c;
if((fp=fopen("d:\\data.txt","w"))==NULL)
{
printf("\nFile can not open!");
getchar();
exit(0);
}
while((c=getchar())!='#')
{
fputc(c,fp);
}
fclose(fp);
}
/*读写字符串*/
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
main(){
FILE *fp;
char c[80]={""},s[80]={""};
/*写字符串*/
if((fp=fopen("d:\\data.txt","w"))==NULL)
{
printf("\nFile can not open!");
exit(0);
}
gets(c);
fputs(c,fp);
fclose(fp);
/*读字符串*/
if((fp=fopen("d:\\data.txt","r"))==NULL)
{
printf("\nFile can not open!");
exit(0);
}
while(!feof(fp))
{
fgets(s,80,fp);
puts(s);
}
fclose(fp);
getchar();
}