【发布时间】:2015-05-20 09:10:40
【问题描述】:
所以我有一个程序,它接收一个列表并将它们放入一个指向每个单词的指针数组中。到目前为止,如果我只是使用 get_lines 函数打印程序的行部分,它会完美地打印 .txt 文件。我只需要帮助按字母顺序对这些单词进行冒泡排序,但我不确定如何。请帮忙!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int readfile(FILE*fp,char**cbuf);
char**get_lines(char *cbuf, int bufsize, int num_word);
int readword(FILE*tmp);
void sortA(char lines,int bufsize,int num_word);
int main(int argc, char*argv[])
{
int i, bufsize, num_word;
char*cbuf;
char**lines;
FILE*fp;
FILE*tmp;
FILE*outfile;
char*newlines;
outfile = fopen("words2.txt","w");
if((fp=fopen(argv[1],"r"))== NULL)
{perror("ERROR: bad/no filename");
exit(0);
}
tmp = fopen(argv[1],"r");
bufsize = readfile(fp,&cbuf);
num_word = readword(tmp);
lines = get_lines(cbuf,bufsize,num_word);
i = 0;
while(newlines[i] != NULL)
{
fprintf(outfile,"%s\n",newlines[i]);
i++;
}
return 0;
}
int readfile(FILE*fp, char**cbuf)
{
int i;
char c;
fseek(fp, 0L, SEEK_END);
int bufsize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
*cbuf = (char *)malloc(sizeof(char) * bufsize +1);
for (i = 0; i < bufsize; i++)
{
c = fgetc(fp);
(*cbuf)[i] = c;
}
return bufsize;
}
int readword(FILE*tmp)
{
int word = 0;
char c;
while((c = fgetc(tmp)) != EOF )
{
if (c == '\n')
word++;
}
return word;
}
char**get_lines(char*cbuf, int bufsize, int num_lines)
{
char **lines = malloc((num_lines + 1) * sizeof *lines);
int line = 0;
while (line < num_lines)
{
lines[line++] = cbuf;
cbuf = strchr(cbuf,'\n');
if (!cbuf)
break;
*cbuf++ = '\0';
}
lines[line] = NULL;
return lines;
}
void SortA(char lines, int bufsize, int num_word)
{
char t[bufsize];
int i,j;
for (i = 1; i < num_word; i++)
{
for (j = 1; j < num_word; j++)
{
if (strcmp(lines[j - 1], lines[j]) > 0)
{
strcpy(t, lines[j - 1]);
strcpy(lines[j - 1], lines[j]);
strcpy(lines[j],t);
}
}
}
【问题讨论】:
标签: c arrays string pointers bubble-sort