C基础文件操作常常遇到,例如 fopen,fputc 等,在其之上可以自己重新定义文件操作,写大作业的过程中需要重写文件输入输出。(大一做的调用linux函数,在win下还是不方便)
于是重写了文件封装。
主要实现的功能:获取文件大小(字节单位),实现无视空格回车等特殊符号的文件流读入(文件结束符EOF除外)
ctqmumu@ctqmumu-laptop:~/桌面/Code/sms$ ./smsfile Filetest/md5.c
0000000000000000000000000000000000000000
0000000000000000000000000000000000000000
0:./smsfile
1:Filetest/md5.c
(nil):0x9819008
file_size:8850(Bytes)
len is 0
copy[30]:
2F2A0D0A202A205468697320636F646520696D706C656D656E7473207468
代码点击查看。
#include
#include
char * getfilecs(char * buffer, int len, FILE *stream)
{
char * temp = buffer;
while (len>0)
{
*temp = fgetc(stream);
if (*temp == EOF) return buffer;
++temp;
--len;
}
printf("len is %d\n",len);
return buffer;
}
int getfilesize(FILE *stream, int *size)
{
fpos_t pos;
fgetpos(stream, &pos);
fseek(stream, 0, SEEK_END);
*size = ftell(stream);
fsetpos(stream, &pos);
return *size;
}
int main(int argc, char *argv[])
{
FILE *fp = NULL;
char buffer[50] = "";
int i;
int file_size;
for (i = 0; i < 40; i++)
printf("%.02X",buffer[i]);
printf("\n");
for (i = 0; i < argc; i++)
{
printf("%d:%s\n", i, argv[i]);
}
printf("%p",fp);
fp = fopen(argv[1],"r");
printf(":%p\n",fp);
if (!fp) return 0;
/************************************/
getfilesize(fp, &file_size);
printf("file_size:%d(Bytes)\n",file_size);
getfilecs(buffer, 30, fp);
printf("copy[30]:\n");
for (i = 0; i < 30; i++)
printf("%.02X",buffer[i],buffer[i]);
printf("\n");
/************************************/
fclose(fp);
}