-
processor fault!!
Hi all,
I have an processor fault while running my code..
The error happens when it reaches files part..
what is the reason of this??
The code
Code:
#include <stdio.h>
typedef struct info* infoptr;
struct info{
char* permission;
char* digit;
char* owner;
char* group;
long int* size;
char* mtime;
char* fname;
infoptr next;
};
void main(){
FILE* fp;
infoptr head;
fp = fopen("info.txt","r");
if( feof(fp))
head = NULL;
else{
infoptr temp_info1, temp_info2;
temp_info1 = new info;
head = temp_info1;
fscanf( fp, "%s", temp_info1->permission );
fscanf( fp, "%s", temp_info1->digit );
fscanf( fp, "%s", temp_info1->owner );
fscanf( fp, "%s", temp_info1->group );
fscanf( fp, "%ld", temp_info1->size );
fscanf( fp, "%s", temp_info1->mtime );
fscanf( fp, "%s", temp_info1->fname );
temp_info1->next = NULL;
while( !feof(fp) ){
temp_info2 = new info;
temp_info1->next = temp_info2;
temp_info1=temp_info2;
fscanf( fp, "%s", temp_info1->permission );
fscanf( fp, "%s", temp_info1->digit );
fscanf( fp, "%s", temp_info1->owner );
fscanf( fp, "%s", temp_info1->group );
fscanf( fp, "%ld", temp_info1->size );
fscanf( fp, "%s", temp_info1->mtime );
fscanf( fp, "%s", temp_info1->fname );
}
temp_info2->next = NULL;
} // end if
}//end main
-
One thing I notice right away:
Code:
fp = fopen("info.txt","r");
if( feof(fp))
That does not check whether or not the fopen() call succeeded. That check will never ever fail the way it's set up. You want to see if fp == NULL after fopen() instead.
-
Almost every line is wrong.
> void main(){
Nope, main returns an int.
> infoptr head;
Your initial list is uninitialised.
> temp_info1 = new info;
new is C++, this is C (apparently)
> fscanf( fp, "%s", temp_info1->permission );
You may have allocated a temp node, but you didn't allocate any for all your pointers inside the structure.
Consider this until you know what you are doing
Code:
struct info{
char permission[100];
char digit[10];
char owner[30];
char group[30];
long int size;
char mtime[20];
char fname[100];
struct infoptr *next;
};
> fscanf( fp, "%ld", temp_info1->size );
This would be
fscanf( fp, "%ld", &temp_info1->size );
Remember that scanf() functions accept only pointers.
Some compilers (gcc and its various ports) will diagnose when you make a mess of printf and scanf functions. Use it.
-
Thank you very much Salem & itsme86..
I changed the code & it works.. Now I can complete my work!!
I should be more careful next time..
Thanks :)