我只想从文件中读取 10 行,然后对它们进行排序并打印出来。但是我的代码有问题,因为当我有这样的文件时:
a
d
b
c
s
(注意 's' 之后的换行符)它的排序文件,但打印 's' 两次:
a
b
c
d
s
s
当我删除换行符时,一切都很好。那么问题出在哪里呢?我的代码中最重要的部分:
void sort(char **array, int filelinecount)
{
int i, j;
char t[LINE_MAX_SIZE];
for(i=1;i<filelinecount;i++)
{
for(j=1;j<filelinecount;j++)
{
if(strcmp(array[j-1], array[j]) > 0)
{
strcpy(t, array[j-1]);
t[LINE_MAX_SIZE] = 0;
strcpy(array[j-1], array[j]);
strcpy(array[j], t);
}
}
}
}
unsigned long int filelinecount = 10;
char **array = (char**)malloc(filelinecount * sizeof(char*));
char singleline[LINE_MAX_SIZE];
int i = 0;
for(i=0; i<filelinecount; i++)
{
fgets(singleline, LINE_MAX_SIZE, fileIN);
array[i] = (char*) malloc (LINE_MAX_SIZE * sizeof(char));
singleline[LINE_MAX_SIZE] = '\0';
strcpy(array[i], singleline);
}
sortfile(array, filelinecount);
for(i=0; i<filelinecount; i++)
{
printf("%s\n", array[i]);
}
好的,我将粘贴我的整个代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 4096
unsigned long int lineCountFile(const char *filename)
{
FILE *fp = fopen(filename, "r");
unsigned long int linecount = 0;
int c;
if(fp == NULL){
fclose(fp);
return 0;
}
while((c=fgetc(fp)) != EOF )
{
if(c == '\n')
linecount++;
}
fclose(fp);
return linecount;
}
void sortfile(char **array, int linecount)
{
int i, j;
char t[MAX_LINE];
for(i=1;i<linecount;i++)
{
for(j=1;j<linecount;j++)
{
if(strcmp(array[j-1], array[j]) > 0)
{
strcpy(t, array[j-1]);
strcpy(array[j-1], array[j]);
strcpy(array[j], t);
}
}
}
}
int main(int argc, char **argv)
{
char *in = "in.txt", *out = "out.txt";
FILE *fileIN, *fileOUT;
fileIN = fopen(in, "r");
if(!fileIN)
{
exit(-1);
}
unsigned long int linecount = lineCountFile(in);
linecount += 1;
char **array = (char**)malloc(linecount * sizeof(char*));
char singleline[MAX_LINE];
int i = 0;
while(fgets(singleline, MAX_LINE, fileIN) != NULL)
{
array[i] = (char*) malloc (MAX_LINE * sizeof(char));
singleline[MAX_LINE] = '\0';
strcpy(array[i], singleline);
i++;
}
sortfile(array, linecount);
for(i=0; i<linecount; i++)
{
printf("%s\n", array[i]);
}
fileOUT = fopen(out, "w");
if(!fileOUT)
{
exit(-1);
}
for(i=0; i<linecount; i++)
{
fprintf(fileOUT, "%s", array[i]);
}
fclose(fileIN);
fclose(fileOUT);
for(i=0; i<linecount; i++)
{
free(array[i]);
}
free(array);
return 0;
}