从文件中读取行并创建按字母顺序排序的数组

我正在学习C,我想做这个特定的任务。 我知道有许多类似的问题和答案,但仍然……我会尝试更具体。 可以说,我有一个包含以下行的文件:

program01 programs aprogram 1program prog 5program 

我现在想要一个数组:

 1program 5program aprogram prog program01 programs 

因此,字符串中只有拉丁文小写字母和数字,没有空格。 我知道如何执行一些单独的步骤,但想要获得并感受整个(和正确的)概念,所以说。 可能它首先从文件中读取时可以做出一些排序决定? 对于我的特定情况,手动排序是首选,只是为了更好的学习和可能的优化。 可以说,一行的最大长度为256,最大行数为256.在此先感谢。

 The following cleanly compiles however, I have not tested it you might want to modify it to get the file name from the command line #include  #include  #include  #define MAX_ROWS (256) #define MAX_COLUMNS (256) #define FILE_NAME "myInputFile" // prototypes void bubbleSortWordsArray( int wordCount ); void printWordsArray( int wordCount ); static char words[MAX_ROWS][MAX_COLUMNS] = {{'\0','\0'}}; int main(void) { FILE *fp = NULL; if( NULL == (fp = fopen( FILE_NAME, "r") ) ) { perror( "fopen failed" ); exit( EXIT_FAILURE ); } // implied else, fopen successful // read each line from file into entry in words array int i = 0; while( fgets(words[i], MAX_COLUMNS, fp ) ) { // remove trailing newline from string words[i][strlen(words[i])-1] = '\0'; i++; } // 'i' contains number of valid entries in words[][] // sort the array of strings bubbleSortWordsArray(i); printWordsArray(i); return(0); } // end function: main void bubbleSortWordsArray( int wordCount ) { int c; // outer index through rows int d; // inner index through rows char swap[MAX_COLUMNS] = {'\0'}; for (c = 0 ; c < ( wordCount - 1 ); c++) { for (d = 0 ; d < (wordCount - c - 1); d++) { if( 0 > strcmp( words[d], words[d+1] ) ) { // then words need to be swapped strcpy( swap, words[d] ); strcpy( words[d], words[d+1]); strcpy( words[d+1], swap ); } // end if compare/swap } // end for } // end for each row } // end function: bubbleSortWordsArray void printWordsArray( int wordCount ) { int i; // loop index printf( "\n" ); // start on new output line for( i=0; i 

检查以下代码:

 #include  #include int main(void) { char a[256][256]; int i=0,j=0,k=0,n; while(i<256 && fgets(a[i],256,stdin) != NULL) { n = strlen(a[i]); if(n >0 && a[i][n-1] == '\n') a[i][n -1] = '\0'; i++; } for(j=0;j 

创建一个2D char数组尝试使用fscanf函数读取它(抱歉,我不记得语法)。 fscan将读取你的整行直到“\ n”,但不应该有空格并将每个字符串连续存储。 然后通过比较每个字符串的第一个索引对其进行排序