linux c编程的问题
//每隔一秒创建一个文件夹,名称为时+分
//在文件夹中每隔一秒创建一个文件,将时间信息写入文件中
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
#include<sys/time.h>
#include<dirent.h>
#include<string.h>
#include<stdio.h>
int creat_dir(char *); //创建文件夹函数
int creat_file(char *,char *,char *); //创建并写入函数
int creat_dir(char *pathname)
{
DIR *p;
int temp; //mkdir返回值
p=opendir(pathname);
if(p=NULL)
{
printf("打开文件夹失败,文件夹不存在\n");
temp=mkdir(pathname,0777);
if(temp==-1)
{
printf("创建文件失败\n");
return -1;
}
else
{
printf("创建文件夹成功\n");
return 0;
}
}
else
{
printf("文件夹已存在\n");
return 0;
}
}
int creat_file(char *pathname,char *filename,char *writebuf)
{
int temp; //chdir返回值
int fd; //文件标识符
int temp_write; //open函数返回值
char wdir[100]; //储存工作路径
temp=chdir(pathname);
if(temp==-1)
{
printf("切换工作路径失败\n");
return -1;
}
else
{
if((getcwd(wdir,100))==NULL)
{
printf("获取工作路径失败\n");
}
printf("工作路径为:%s\n",wdir);
fd=open(filename,O_RDWR|O_CREAT,S_IRWXU);
//以传入名字创建文件
if(fd==-1)
{
printf("创建文件失败\n");
return -1;
}
else
{
printf("创建文件成功\n");
temp_write=write(fd,writebuf,strlen(writebuf));
if(temp_write==-1)
{
printf("写入失败\n");
close(fd);
return -1;
}
else
{
printf("写入成功\n");
close(fd);
return 0;
}
}
}
}
int main()
{
int temp_creat; //创建文件夹函数返回值
int temp_file; //创建文件返回值
char dirname[10]="DIR"; //目录名
char filename[10]="File"; //文件名
char writebuf[15]; //写入缓冲区
time_t timetemp; //时间变量
struct tm *time_str; //时间结构体
char timebuf[3]; //待连接入的时间信息
char timebuf_2[3];
time(&timetemp);
time_str=gmtime(&timetemp); //存入结构体时间中
sprintf(timebuf_2,"%02d",time_str->tm_min);
strcat(dirname,timebuf_2); //文件夹名称加入时间信息
temp_creat=creat_dir(dirname); //调用创建文件夹函数
if(temp_creat==-1) //创建失败
{
return 1;
}
else
{
sprintf(writebuf,"%s\n",ctime(&timetemp)); //将时间信息加入到writebuf中
sprintf(timebuf,"%02d",time_str->tm_sec);
strcat(filename,timebuf); //文件名称加入时间信息
temp_file=creat_file(dirname,filename,writebuf);
//调用创建文件函数
if(temp_file==-1) //创建失败
{
return 2;
}
else
{
return 0;
}
}
}
运行结果是
文件夹已存在
切换工作路径失败
已放弃(核心转储)
我gdb调试了下 打开文件夹那里 明明文件夹不存在 为什么返回的指针p不是NULL 纠结了很久 新手 求大神指点