天天看點

C語言自制檔案分割器(簡單)

記得國中的時候用MP3看電子書,MP3支援的文本文檔格式不能超過1M,否則打不開,然後在網上下了一個檔案分割器,感覺真的很強大啊(别吐槽,當時真的很白)。

等自己學了C語言後,便想自己弄一個檔案分割器,可是在網上搜了一下源碼,看起來很複雜的樣子,也就沒了興趣。現在又重新拾起了這個願望,不過第一次弄的比較簡單,沒有重命名等功能,以後還會重新附加功能的。

有什麼不足的,歡迎拍磚。

閑話少叙,直接上源代碼。

/* copy the file1 into 2 file --------
 * file2 && file3
 * And then print file2 && file3
 */


#include <stdio.h>
#include <stdlib.h>


int main(void)
{
	FILE *fp1 ,*fp2,*fp3;
	int ch;
	int row_count = 0; //count the rows
	
	if ( (fp1 = fopen ("file1","r+")) == NULL) {
		perror ("open file file1\n");
		exit(1);
	}


	if ( ( fp2 = fopen ("file2", "w+")) == NULL) {
		perror ("open file file2\n");
		exit(1);
	}


	if ( ( fp3 = fopen ("file3", "w+")) == NULL) {
		perror ("open file file3\n");
		exit(1);
	}

	//count the row of the file
	while ((ch = fgetc (fp1)) != EOF ){
		if (ch == '\n') row_count++;
	}
	
	rewind(fp1);
	
	//copy file1 into two files----file2 && file3
	while ((ch = fgetc (fp1)) != EOF){
		static int copy_row_count = 0;
		if (ch == '\n') copy_row_count++;

		if (copy_row_count <= row_count/2) {fputc (ch, fp2); continue;}
		if (copy_row_count >  row_count/2) {fputc (ch, fp3); continue;}
	}


	rewind(fp1);
	rewind(fp2);
	rewind(fp3);


	printf("#########\nfile1:\n#########\n");
	while ((ch = fgetc(fp1)) != EOF )
		putchar(ch);
	
	
	printf("#########\nfile2:\n#########\n");
	while ((ch = fgetc(fp2)) != EOF )
		putchar(ch);
	
	printf("#########\nfile3:\n#########\n");
	while ((ch = fgetc(fp3)) != EOF )
		putchar(ch);
	
	fclose(fp1);
	fclose(fp2);
	fclose(fp3);


	return 0;
}
           

歡迎大家指正批評!!