C programming language files topic (b)

1. There are two disk files A and B, each line of characters is stored, the information required these two files are merged (in alphabetical order), output to a new file in the C

Analysis: For this subject my thinking is to first read the contents of the two files are stored in AB 2 array, then the two string arrays spliced ​​using strcat () function, and finally after the mosaic sorting strings on it.

[Show] Code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
	int len;
	FILE *p1,*p2,*p3;
	char s1[100],s2[100];
	p1 = fopen("E:\\A.txt","r");
	p2 = fopen("E:\\B.txt","r");
	p3 = fopen("E:\\C.txt","w");
	if(!p1) {
		printf("文件不存在!");
		exit(0);
	}
	fgets(s1,99,p1);//将A中字符串写入到s1数组中
	fclose(p1);
	if(!p2) {
		printf("文件不存在!");
		exit(0);
	}
	fgets(s2,99,p2);//将B中字符串写入到s2数组中
	fclose(p2);
	strcat(s1,s2);//字符串拼接,s2拼接到s1后面
	len = strlen(s1);//求拼接后字符串长度
	for(int i=0; i<len-1; i++) {//字符串排序
		for(int j=0; j<len-1-i; j++) {
			if(s1[j] > s1[j+1]) {
				char t = s1[j];
				s1[j] = s1[j+1];
				s1[j+1] = t;
			}
		}
	}
	if(!p3) {
		printf("文件不存在!");
		exit(0);
	}

	fputs(s1,p3);//输出字符串 
	fclose(p3); 
}

【operation result】

(1) look at the contents of the file A.txt

(2) look at the contents of the file B.txt

(3) spliced ​​content in the sorted file C.txt

 

He published 196 original articles · won praise 581 · views 470 000 +

Guess you like

Origin blog.csdn.net/wyf2017/article/details/105195548