//每隔一秒創建一個檔案夾,名稱為時+分
//在檔案夾中每隔一秒創建一個檔案,將時間資訊寫入檔案中
#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 糾結了很久 新手 求大神指點
uj5u.com熱心網友回復:
先用管理員權限執行程式試看看,程式不一定有權限創建目錄或檔案的。uj5u.com熱心網友回復:
Hi Feng,In your`s code :
if(p=NULL)
you mean to be:
if(p==NULL)
uj5u.com熱心網友回復:
樓主現在這個問題解決了嗎 能否分享一下uj5u.com熱心網友回復:
yes thanks
uj5u.com熱心網友回復:
解決了 就是樓上說的那樣
uj5u.com熱心網友回復:
用shell寫更簡單吧uj5u.com熱心網友回復:
這錯誤比較低級,但是是經常犯的uj5u.com熱心網友回復:
if判斷這樣寫 if (NULL == p) 這樣可以防止比較符號寫成賦值符號uj5u.com熱心網友回復:
樓上的建議一看就是老手了uj5u.com熱心網友回復:
在CSDN遇到很多把“=”當成“==”的情況了。uj5u.com熱心網友回復:
全是坑啊。不是在改BUG就是在寫BUGuj5u.com熱心網友回復:
所以所 if判斷還是需要if(NULL == p) 比較安全點uj5u.com熱心網友回復:
這個建議不錯
uj5u.com熱心網友回復:
很實用的技巧,學習了!uj5u.com熱心網友回復:
哈哈哈!受教了uj5u.com熱心網友回復:
我也覺得用shell 幾行就搞定了 ,或者在程式中直接用system呼叫uj5u.com熱心網友回復:
if(p) 就行了,現在編譯器都支持,如果記得NULL == p 當然好,但一般想得起這么寫,那估計正向寫也不會忘了。。。uj5u.com熱心網友回復:
這個可以的, if里面的語法問題uj5u.com熱心網友回復:
老手不會寫錯轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/123545.html
標籤:驅動程序開發區
