Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 99

C Exercise 99

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** There are two disk files A and B, each storing a line of letters. Merge the information from these two files (in alphabetical order) and output it to a new file C.

**Program analysis:** You need to create A.txt and B.txt first.

Contents of A.txt:

123

Contents of B.txt:

456

Program source code:

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

#include

<

stdlib.h

#include

<

string.h

int

main

(

)

{

FILE

fa

,*

fb

,*

fc

;

int

i

,

j

,

k

;

char

str

[

100

]

,

str1

[

100

]

;

char

tem

;

if

(

(

fa

=

fopen

(

"

A.txt

"

,

"

r

"

)

)

==

NULL

)

// A.txt must exist

{

printf

(

"

error: cannot open A file!

\

n

"

)

;

exit

(

0

)

;

}

fgets

(

str

,

99

,

fa

)

;

fclose

(

fa

)

;

if

(

(

fb

=

fopen

(

"

B.txt

"

,

"

r

"

)

)

==

NULL

)

// B.txt must exist

{

printf

(

"

error: cannot open B file!

\

n

"

)

;

exit

(

0

)

;

}

fgets

(

str1

,

100

,

fb

)

;

fclose

(

fb

)

;

strcat

(

str

,

str1

)

;

for

(

i

=

strlen

(

str

)

1

;

i

1

;

i

--

)

for

(

j

=

0

;

j

<

i

;

j

++

)

if

(

str

[

j

]

str

[

j

1

]

)

{

tem

=

str

[

j

]

;

str

[

j

]

=

str

[

j

1

]

;

str

[

j

1

]

=

tem

;

}

if

(

(

fc

=

fopen

(

"

C.txt

"

,

"

w

"

)

)

==

NULL

)

// Merge into C.txt

{

printf

(

"

error: cannot open C file!

\

n

"

)

;

exit

(

0

)

;

}

fputs

(

str

,

fc

)

;

fclose

(

fc

)

;

system

(

"

pause

"

)

;

return

0

;

}

After running the above example, open C.txt; its contents are as follows:



123456

100 Classic C Language Examples 100 Classic C Language Examples