【发布时间】:2015-01-27 05:14:02
【问题描述】:
我正在尝试按名称对文件的内容进行排序 这是代码
#include <iostream>
#include<string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Contacts
{
char name[20];
int phone;
char address[20];
};
int countLines(FILE * fp);
void sort_contact(int length , FILE * f);
int main(int argc, char** argv) {
FILE *f=fopen("D:\\eman.txt","r");
int c;
c=countLines(f);
printf("number of lines %d",c);
sort_contact(c , f);
return 0;
}
int countLines(FILE * fp){
char line[80];
int counter = 0;
while ( fgets(line, sizeof line, fp) ){
counter+=1;
}
return counter;
}
void sort_contact(int length , FILE * f)
{
// struct Contacts * eman [length];
int flag;
int i; // for loop counter
struct Contacts con;
struct Contacts tmp;
struct Contacts conn;
struct Contacts users[length];
//f=fopen("","r";)
//while( ( fscanf(f, "%s %d %s ", con.name ,&con.phone,con.address) != EOF) && (length > 0) )
while( ( fscanf(f, "%s %d %s ", users[length].name ,&users[length].phone,users[length].address) != EOF) && (length > 0) )
{
con=users[length];
conn=users[length--];
flag=strcmp(con.name,conn.name);
//length --;
switch(flag)
{
case 1:
tmp=users[length--];
users[length--]=users[length];
users[length]=tmp;
break;
case 0:
case -1:
break;
}
length --;
//seek(fd, 0, SEEK_END);
}//end fo while
fclose(f);
f=fopen("D:\\eman.txt","+w");
for(i=length;i>0;i--)
{
// tmp=users[i];
fprintf(f,"%s %d %s",users[i].name,users[i].phone, users[i].address);
}
fclose(f);
}
我将内容放在一个结构中,然后按名称对结构进行排序并再次将其添加到文件中 当我运行它时,文件中没有任何变化
【问题讨论】:
-
什么?
iostreamC 程序的标头? -
2)
Type array[Size];对array[Size]的访问权限超出范围。 -
FILE *f=fopen("D:\\eman.txt","r");...如果fopen()失败怎么办? -
我尝试更改 while 循环并放置两个 for 循环,但没有任何改变我想比较两行 for(i=0;i
-
您的代码看起来并不像排序算法,长度也是 - 在 while 循环中被调用了 3 次,这似乎是不正确的。