Segmentation fault (core dumped) linux C编程,50分
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include </home/hanyu/test/ftw.h>
int levelnum;
void createLog(char *sourceDir, char *logFilePath)
{
DIR* dir;
char* d1="DT_REG";
char* d2="DT_DIR";
char* from_file;
char *info;
struct dirent *ptr;
int from_num;
char* filename;
int soulog,num1,num2=0;
char* b1="/";
char* b2="\0";
char* b3="\t";
char* b4="\r\n";
off_t off;
struct stat *ptr1;
char* time1;
char* time2;
char numc[4];
long numchar;
char* numptr=numc;
dir=opendir(sourceDir);
from_num=strlen(sourceDir);
if((soulog=open(logFilePath,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))==-1)
{
printf("FAILED TO OPEN ### %s ###\n",logFilePath);
return;
}
while((ptr=readdir(dir))!=NULL){
if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0)
continue;
filename=ptr->d_name;
num1=from_num+strlen(filename)+2;
from_file=(char*)malloc(num1);
strcpy(from_file,sourceDir);
strcat(from_file,b1);
strcat(from_file,filename);
printf("aaaaaaaaaaaaa\n");
printf("%s\n",from_file);
if(stat(from_file,ptr1)==-1)
{
printf("kill\n");
return;
}
time1=ctime(&(ptr1->st_atime));
time2=ctime(&(ptr1->st_mtime));
printf("88888888888888\n");
if(ptr->d_type==DT_DIR){
numchar=1;sprintf(numptr,"%ld",numchar);
num2=11+strlen(filename)+strlen(time1)+strlen(time2);
info=(char*)malloc(num2);
strcpy(info,d2);
strcat(info,b3);
strcat(info,numptr);
strcat(info,b3);
strncat(info,time1,24);
strcat(info,b3);
strncat(info,time2,24);
strcat(info,b3);
strcat(info,filename);
strcat(info,b4);
off=lseek(soulog,0,SEEK_END);
if(write(soulog,info,num2)==-1){
printf("WRITE DIR FAIL");
close(soulog);
return;
}
printf("%s",info);
free(info);
createLog(from_file,"/home/userData/cs240.Log");
free(from_file);
}
if(ptr->d_type==DT_REG)
{
num2=8+strlen(filename);
info=(char*)malloc(num2);
strcpy(info,d1);
strcat(info,b3);
strcat(info,filename);
strcat(info,b4);
printf("%s",info);
off=lseek(soulog,0,SEEK_END);
if(write(soulog,info,num2)==-1){
printf("WRITE REG FAIL");
close(soulog);
return;
}
free(info);
free(from_file);
}
}
close(soulog);
if(closedir(dir)==-1){
printf("fail to kill dir\n");
return;
}
}
int main(void)
{
char* p="/home/userData/cs240";
char* q="/home/userData/cs240.Log";
createLog(p,q);
return 0;
}