fread和fwrite字节不足怎么办?
假如我们定义了个char[100];然后打开文件调用fread进行读操作再打开另外文件进行fwrite操作那么我们的形式应该是
fread(a,100,1,in);
fwrite(a,100,1,out);
但是如果输入的文件的字节数不是100的倍数,则出现在输出文件内用乱码填充到100字节的倍数,也就是如果文件没有100个字节fread和fwrite也要强制读写100个字节吗?
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <assert.h> int main(int argc , char *argv[]) { FILE * fpin , * fpout ; long krd , kwt , index ; char * buffer ; if (argc != 3) { fprintf(stderr , "\n%s %s %s\n" , "Usage:" , "cp resourefile" ,"/path/targetfile") ; exit(1) ; } fpin = fopen(argv[1] , "rb") ; fpout = fopen(argv[2] , "ab") ; fseek(fpin , 0L , SEEK_END) ; index = ftell(fpin) ; fseek(fpin , 0L , SEEK_SET) ; buffer = (char *)malloc(index) ; assert(buffer) ; while ((krd = fread(buffer , index , 1 , fpin)) ) { kwt = fwrite(buffer , index , 1 , fpout) ; if (kwt != krd) { perror("file copy error") ; exit(1) ; } } fclose(fpin) ; fclose(fpout) ; return 0 ; }
/*stack.h*/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> #ifndef _STACK_H_ #define _STACK_H_ typedef long FileSize ; typedef struct Node * PtrToNode ; typedef struct Node { FileSize item ; PtrToNode next ; }Node ; typedef struct Stack { PtrToNode top ; }Stack ; PtrToNode MakeNode(void) ; void CreateStack(Stack * sp) ; bool IsStackEmpty(Stack * sp) ; void Push(Stack * sp , FileSize size) ; FileSize Pop(Stack * sp) ; #endif
/*stack.c*/ #include "stack.h" PtrToNode MakeNode(void) { static PtrToNode nptr = NULL ; nptr = (PtrToNode)malloc(sizeof(Node)) ; assert(nptr) ; nptr->next = NULL ; return nptr ; } void CreateStack(Stack *sp) { sp->top = MakeNode() ; return ; } bool IsStackEmpty(Stack * sp) { return sp->top->next == NULL ; } void Push(Stack * sp , FileSize size) { PtrToNode np ; sp->top->item = size ; np = MakeNode() ; np->next = sp->top ; sp->top = np ; return ; } FileSize Pop(Stack * sp) { PtrToNode np ; FileSize item ; np = sp->top->next ; item = np->item ; free(sp->top) ; sp->top = np ; return item ; }
/*main.c*/ #include "stack.h" #define SPLSIZE (1024 * 1024) /*split base on 1 megabyte */ #define Prompt "Please waitting...\r" int main(int argc , char *argv[]) { char * buffer ; FileSize size , crd , cwt ; Stack stack ; FILE * fpsrc , * fptar ; if (argc != 3) { fprintf(stderr , "\n%s%s\n" , "Usage: " , "cp resourcefile /path/targetfile") ; exit(1) ; } CreateStack(&stack) ; fpsrc = fopen(argv[1] , "rb") ; fptar = fopen(argv[2] , "ab") ; fseek(fpsrc , 0L , SEEK_END) ; size = ftell(fpsrc) ; fseek(fpsrc , 0L , SEEK_SET) ; if (size % SPLSIZE) { Push(&stack , size % SPLSIZE) ; size -= size % SPLSIZE ; } while (size) { Push(&stack , SPLSIZE) ; size -= SPLSIZE ; } while(!IsStackEmpty(&stack)) { printf(Prompt) ; size = Pop(&stack) ; buffer = (char *)malloc(size) ; crd = fread(buffer , size , 1 , fpsrc) ; cwt = fwrite(buffer , size , 1 , fptar) ; if (crd != cwt) { fprintf(stderr,"Copy file error\n") ; exit(1) ; } free(buffer) ; } fclose(fpsrc) ; fclose(fptar) ; return 0 ; }