C/C++文件读与写(函数fopen,fwrite,fprintf,fgetc,fputc,fgets,fclose)

来源:互联网 发布:淘宝店铺尺寸 编辑:程序博客网 时间:2024/05/29 13:27

<一>文件的打开与关闭


1.打开fopen

FILE * fopen(char *filename,char *mode);


2.关闭fclose

int fclose(FILE *fp);


<二>文件的读写

1.fputc与fgetc

写与读字符

int fgetc(FILE *fp);

int fputc(char ch,FILE *fp);


2.fread与fwrite

fwrite和fread是以记录为单位的I/O函数,fread和fwrite函数一般用于二进制文件的输入输出。

  1. #include <stdio.h>  
  2. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);  
  3. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); 

3.fprintf
int fprintf( FILE *stream, const char *format, ... );
fprintf()函数根据指定的format(格式)发送信息(参数)到由stream(流)指定的文件. fprintf()只能和printf()一样工作. fprintf()的返回值是输出的字符数,发生错误时返回一个负值.


示例一:
#include<stdio.h>
#include<string.h>
int main(void)
{
    FILE*stream;
    char msg[]="this is a test";
    char buf[20];
    if((stream=fopen("DUMMY.FIL","w+"))==NULL)
    {
        fprintf(stderr,"Can not open output file.\n");
        return 0;
    }
    /*write some data to the file*/
    fwrite(msg,strlen(msg)+1,1,stream);
    /*sizeof(char)=1 seek to the beginning of the file*/
    fseek(stream,0,SEEK_SET);
    /*read the data and display it*/
    fread(buf,strlen(msg)+1,1,stream);
    printf("%s\n",buf);
    fclose(stream);
    return 0;
}

示例二:

       FILE* fp;

       fp = fopen("g:\\thermal.txt", "w");
       if (!fp)
          {
           perror("cannot open file");
           exit(-1);
         }


       for (n=0;n<41;n++)
          {
           for (m=0;m<61;m++)
            {
             fprintf(fp, "%10f  ", t[n][m]);
             }
           fputc('\n', fp);
           }

       for (m=0;m<61;m++)
            {
             fprintf(fp, "n=20    %-10.8f ", t[20][m]);
             fputc('\n', fp);
             }

       for (n=0;n<41;n++)
          {
           fprintf(fp, "m=30     %-10.8f ", t[n][30]);
           fputc('\n', fp);
           }
       fclose(fp);
   }                 /*数据文件输出*/


<三>文件尾测试函数

int  feof(FILE *fp)

EOF 是在头文件stdio.h中定义的符号常量,常数值为-1.

<四>改变文件位置指针函数

fseek(FILE *fp,Long offset,int position)

offset  位移量

position 起始量

fseek(fp,30L,0)

<五>文件头定位函数

void rewind(FILE *fp);

rewind(fp);


文件的写:

//获取文件指针
FILE *pFile = fopen("1.txt", //打开文件的名称
                    "w"); // 文件打开方式 如果原来有内容也会销毁
//向文件写数据
fwrite ("hello", //要输入的文字
         1,//文字每一项的大小 以为这里是字符型的 就设置为1 如果是汉字就设置为4
         strlog("hello"), //单元个数 我们也可以直接写5
         pFile //我们刚刚获得到的地址
         );
//fclose(pFile); //告诉系统我们文件写完了数据更新,但是我们要要重新打开才能在写

fflush(pFile); //数据刷新 数据立即更新


文件的读:

FILE *pFile=fopen("1.txt","r"); //获取文件的指针
char *pBuf;  //定义文件指针
fseek(pFile,0,SEEK_END); //把指针移动到文件的结尾 ,获取文件长度
int len=ftell(pFile); //获取文件长度
pBuf=new char[len+1]; //定义数组长度
rewind(pFile); //把指针移动到文件开头 因为我们一开始把指针移动到结尾,如果不移动回来 会出错
fread(pBuf,1,len,pFile); //读文件
pBuf[len]=0; //把读到的文件最后一位 写为0 要不然系统会一直寻找到0后才结束
MessageBox(pBuf);  //显示读到的数据
fclose(pFile); // 关闭文件





0 0