当14楼透明的呢
授人以渔,不授人以鱼。
#include <stdio.h> #include <stdlib.h> #define MAX 8 int file(void) { char *buffer = (char*)malloc(MAX); char *temp = NULL; size_t count = 0; size_t size = MAX; char answer = 0; size_t i = 0; FILE *pfile = NULL; char *filename = "F:\\vc\\666.txt"; if(!(pfile = fopen( filename, "wb"))) { printf("创建文件%s失败!\n",filename); return -1; } for(;;) { printf("您%s输入字符串吗?(y/n):", count == 0? "想":"不想"); scanf(" %c",&answer); fflush(stdin); if(answer == 'n' || answer == 'N') break; fflush(stdin); while((buffer[count++] = getchar()) != '\n') { if(count == size) { size += MAX; temp = (char*)malloc(size); for(i=0;i<count;i++) temp[i] = buffer[i]; free(buffer); buffer = temp; temp = NULL; } } fwrite(&count, sizeof(count), 1, pfile); fwrite(buffer, sizeof(char), count, pfile); count = 0; } fclose(pfile); return 0; } int main(void) { size_t str_count = 0; fpos_t *postition = NULL; char *buffer = NULL; size_t length = 0; int jilu = 0; char *temp = NULL; int i = 0; char *Input_filename = "F:\\vc\\666.txt"; char *Out_filename = "F:\\vc\\222.txt"; FILE *Input_pfile = NULL; FILE *Out_pfile ; file(); if(!(Input_pfile = fopen(Input_filename, "rb"))) { printf("读取文件%s faild!\n",Input_filename); return 1; } /* 得到字符串数目 */ while(1) { fread(&length, sizeof(size_t), 1, Input_pfile); if(feof(Input_pfile)) break; if( jilu < (int)length) { jilu = length; temp = buffer; free(temp); temp = NULL; buffer = (char*)malloc(length+1); } fread(buffer, sizeof(char), length, Input_pfile); str_count++; } printf("The count of strings are %d\n",str_count); postition = (fpos_t*)malloc(str_count-1); rewind(Input_pfile); fread(&length, sizeof(size_t), 1, Input_pfile); fread(buffer, sizeof(char), length, Input_pfile); for(i=0;i<(int)str_count-1;i++) { fgetpos(Input_pfile, &postition[i]); fread(&length, sizeof(size_t), 1, Input_pfile); fread(buffer, sizeof(char), length, Input_pfile); } printf("\nEE\n"); Out_pfile = fopen("F:\\vc\\222.txt","wb"); /* 在这里出错了,少于11个字符运行到这里会出警告 */ printf("\nEE\n"); for(i=0;i<(int)str_count-1;i++) { fsetpos(Input_pfile, &postition[str_count-2-i]); fread(&length, sizeof(size_t), 1, Input_pfile); fwrite(&length, sizeof(size_t), 1, Out_pfile); fread(buffer, 1, length, Input_pfile); fwrite(buffer, 1, length, Out_pfile); } rewind(Input_pfile); fread(&length, sizeof(size_t), 1, Input_pfile); fwrite(&length, sizeof(size_t), 1, Out_pfile); fread(buffer, 1, length, Input_pfile); fwrite(buffer, 1, length, Out_pfile); fclose(Out_pfile); fclose(Input_pfile); Out_pfile = fopen(Out_filename, "rb"); printf("The strings in the %s are:\n",Out_filename); for(i=0;i<(int)str_count;i++) { fread(&length, sizeof(size_t), 1, Out_pfile); fread(buffer, sizeof(char), length, Out_pfile); buffer[length] = '\0'; printf("%s\n",buffer); } fclose(Out_pfile); remove(Input_filename); remove(Out_filename); return 0; }这是我鼓秋一下午弄出来的代码,我对他寄予厚望,可是我却弄出个怪胎来,或许只是我才疏学浅不明就里吧,上面是我的代码。