C语言操作文件总结

#include "stdio.h"
#include "malloc.h"
#include <sys/stat.h>
//获取文件大小
long GetSize(char* path)
{
    //第一种方法获取文件大小
    long currentPosition;
    long size;
    FILE *fp;    
    fp=fopen(path,"rb");
       /* Save the current position. */
       currentPosition = ftell(fp);
       /* Jump to the end of the file. */
       fseek( fp, 0L, SEEK_END );
       /* Get the end position. */
       size = ftell( fp );
       /* Jump back to the original position. */
       fseek( fp, currentPosition, SEEK_SET );
       return size;

    //第二种方法获取文件大小,需要引用sys/stat.h
    /*struct stat buf;
    if( stat(path, &buf ) != -1 ) {
        return buf.st_size;
    }
    return -1;*/

       fclose(fp);
}

void ReadTxt(char *path)
{
    FILE *file=fopen(path,"rt");
    if(file==NULL)
    {
        printf("文件不存在\n");
        return;
    }
    //下面两种方式本质都是分配一个10字节的存储单元,然后声明一个字符指针指向第一个字节的内存地址,在以读文本文件方式打开文件后,从中读出9个字符送入str数组,在数组最后一个单元内将加上'\0',然后在屏幕上显示输出str数组。    
    //或者 char str[10];
    char *str=(char *)malloc(10);
    fgets(str,10,file);
    //只会输出9个字符
    printf(str);
    printf("\n");
    fclose(file);
    free(str);
    str=NULL;
}

//读取字符
void ReadChar(char *path)
{
    FILE *file=fopen(path,"rt");
    char c;
    if(file==NULL)
    {
        printf("文件不存在\n");
        return;
    }
    //fgetc与getc一样,fputc与putc一样
    while((c=getc(file))!=EOF)
    {
        printf("%c",c);        
    }    
    printf("\n");
    fclose(file);
}

void ReadTxtByLength(char *path)
{
    //因为使用fgets方法会在字符数组最后加'\0',所以这里是GetSize(path)+1
    long length=GetSize(path)+1;

    FILE *file=fopen(path,"rt");
    if(file==NULL)
    {
        printf("文件不存在\n");
        return;
    }
    //下面两种方式本质都是分配一个10字节的存储单元,然后声明一个字符指针指向第一个字节的内存地址,在以读文本文件方式打开文件后,从中读出9个字符送入str数组,在数组最后一个单元内将加上'\0',然后在屏幕上显示输出str数组。    
    //或者 char str[10];
    char *str=(char *)malloc(length);
    fgets(str,length,file);
    //只会输出9个字符
    printf(str);
    printf("\n");
    fclose(file);
    free(str);
    str=NULL;
}
#define type void
//复制文件
void CopyFile(char *originalPath,char *desPath)
{
    long length=GetSize(originalPath);
    //这里使用任何指针类型都可以,如int,char,FILE,void等等
    type *buffer=(type *)malloc(length);
    FILE *fp=fopen(originalPath,"rb");
    fread(buffer,length,1,fp);
    fclose(fp);

    FILE *newFile=fopen(desPath,"wb");
    fwrite(buffer,length,1,newFile);
    fflush(newFile);
    fclose(newFile);

}

void main()
{
    //ReadChar("D:\\1.txt");
    //ReadTxt("D:\\1.txt");
    //ReadTxtByLength("D:\\c.txt");
    CopyFile("D:\\a.rar","D:\\b.rar");
}
posted @ 2010-09-14 23:15  再快一点  阅读(256)  评论(0编辑  收藏  举报