|
Read the contents of two files (str1.txt str2.txt) (both contain only a string of characters), store them in an array and sort them into a newly created file (newstr.txt)
Sorting and writing are all right, but when reading, you need to add i- = 1 (the following is marked ~). If you do n’t add it, there will be an extra character at the end after two reads and writes. For example, if str1 is qwert, str2.txt is asdfg, then without i- = 1, the result is:
×× ADEFGQRSTW (× stands for random characters, and a small y similar to the phonetic symbol is displayed during debugging)
That is, QWERT × ASDFG ×
#include <stdio.h>
#define NAMELEN 10
#define F_NAMELEN 10
#define STRLEN 100
#define NULL 0
void main ()
{
FILE * fp;
int i = 0, j, min, temp, length;
char ch, allstr [STRLEN], r1 [F_NAMELEN], r2 [F_NAMELEN], w1 [F_NAMELEN];
printf ("Input File1 (str1.txt) please\n =>"); // Enter the name of the first file to be read
scanf ("% s", r1);
if ((fp = fopen (r1, "r")) == NULL)
{
printf ("File open failed\n");
exit (0);
}
while (! feof (fp))
allstr [i ++] = fgetc (fp);
i- = 1; // If not, there will be one more random character at the end. Why? Is the judgment condition wrong?
printf ("Input File2 (str2.txt) please\n =>"); // Enter the name of the second file to be read
scanf ("% s", r2);
if ((fp = fopen (r2, "r")) == NULL)
{
printf ("File open failed\n");
exit (0);
}
while (! feof (fp))
allstr [i ++] = fgetc (fp); // Save the characters in the file into an array and sort
allstr [i-1] = '\0'; // i-1 must also be used here
length = strlen (allstr);
for (i = 0; i <length-1; i ++) // sort characters
{
for (min = i, j = i + 1; j <length; j ++)
if (allstr [j] <allstr [min])
min = j;
if (min! = i)
{
temp = allstr [i];
allstr [i] = allstr [min];
allstr [min] = temp;
}
}
printf ("Input new file name (NewStr.txt) please\n =>");
// Enter the name of the file to be written
scanf ("% s", w1);
if ((fp = fopen (w1, "w")) == NULL)
{
printf ("File open failed\n");
exit (0);
}
i = 0;
while (allstr [i])
fputc (allstr [i ++], fp);
fclose (fp);
} |
|