系统编程(数据库)

来源:互联网 发布:java反射调用方法 编辑:程序博客网 时间:2024/04/30 12:50

FILE *  指针  

文件打开成功,则返回被打开文件的指针。若文件打开失败,返回NULL;


fopen(文件名,权限)

如fopen(“a.txt”,"r")   权限分只读,只写,追加


程序1::从指定的文件中读一个字符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char ch;


if( (fp = fopen("f.txt","r")) == NULL)
{
printf("Cannot open file\n");
exit(1);
}


ch = fgetc(fp);


while(ch != EOF)
{
putchar(ch);
ch = fgetc(fp);
}


fclose(fp);


    return 0;
}

程序2:将字符串写入到文件中

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main()
{
FILE *fp;
char ch;


if( (fp = fopen("h.txt","w")) == NULL)
{
   printf("Cannot open file");
exit(-1);
}


ch = getchar();
while(ch != '\n')
{
fputc(ch,fp);
ch = getchar();
}


printf("\n");
fclose(fp);




    return 0;
}

这里写到一个文件中只能cat查看

程序3 :拷贝
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main()
{
FILE *fp1;
FILE *fp2;
char ch;


if((fp1 = fopen("j.txt","r")) == NULL)
{
printf("cannot open file");
exit(-1);
}


if((fp2 = fopen("k.txt","w")) == NULL)
{
printf("Cannot open file");
exit(-1);
}


ch = fgetc(fp1);


while(ch != EOF)
{
fputc(ch,fp2);
ch = fgetc(fp1);
}


    return 0;
}


0 0
原创粉丝点击