我的编程有问题,我完全不知道为什么我不能在程序中使用qsort以有序的方式对这些struct数组进行排序?可以用某种方式帮助我吗?在这个程序中,有4个节点,每个节点代表一个文件,节点有文件名,大小和文件类型。我想根据文件名对它进行排序,但我完全不知道为什么qsort根本不起作用!
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
//int cmp(const void *a,const void*b);
typedef struct node
{
char filename[255];
char filetype[255];
long ofilesize;
long newfilesize;
}Node;
Node Line[4];
int cmp(const void *a,const void*b)
{
return strcmp(((Node *)a)->filename,((Node *)b)->filename);
}
int main(){
/* int j=0;
for(;j<4;j++){
Line[j]=(Node*)malloc(sizeof(Node));
}*/
strcpy(Line[0].filename,"b.txt");
strcpy(Line[1].filename,"c.txt");
strcpy(Line[2].filename,"d.txt");
strcpy(Line[3].filename,"e.txt");
int i=0;
for(;i<4;i++){
strcpy(Line[i].filetype,"regular file");
Line[i].ofilesize=i;
Line[i].newfilesize=i;
}
for(i=0;i<4;i++)
{
printf("File %s has type %s original size %ld new size %ld \n",Line[i].filename,Line[i].filetype,Line[i].ofilesize,Line[i].newfilesize);
}
qsort((void *)&Line,4,sizeof(Node),cmp);
for(i=0;i<4;i++)
{
printf("File %s has type %s original size %ld new size %ld \n",Line[i].filename,Line[i].filetype,Line[i].ofilesize,Line[i].newfilesize);
}
}
这是我的输出:
File b.txt has type regular file original size 0 new size 0
File c.txt has type regular file original size 1 new size 1
File d.txt has type regular file original size 2 new size 2
File e.txt has type regular file original size 3 new size 3
File b.txt has type regular file original size 0 new size 0
File c.txt has type regular file original size 1 new size 1
File d.txt has type regular file original size 2 new size 2
File e.txt has type regular file original size 3 new size 3
答案 0 :(得分:1)
被删除的评论作者所说的是
int cmp(Node *a,Node *b) {
return strcmp(a->filename,b->filename);
}
应该是
int cmp(Node **a,Node **b) {
return strcmp((*a)->filename,(*b)->filename);
}
如果你想保留你的指示。
答案 1 :(得分:1)
使用C ++ 11很容易解决。让编译器为你处理内存分配,并避免所有那些讨厌的指针。
#include <array>
#include <string>
#include <algorithm>
struct Node
{
std::string filename;
std::string filetype;
long ofilesize;
long newfilesize;
};
bool CompareByFilename(const Node& lhs, const Node& rhs)
{
return lhs.filename < rhs.filename;
}
int main()
{
std::array<Node, 4> line;
line[0].filename = "e.txt";
line[1].filename = "d.txt";
line[2].filename = "c.txt";
line[3].filename = "b.txt";
for (unsigned int i = 0; i < line.size(); i++)
{
line[i].filetype = "regular file";
line[i].ofilesize = i;
line[i].newfilesize = i;
}
std::sort(line.begin(), line.end(), CompareByFilename);
}
考虑使用枚举作为文件类型,您确定long
总是足够大以容纳文件大小吗?