linux c建立資料夾,並在資料夾中建立檔案
************************************************************************************************************
建立資料夾,在在檔案裡面建立檔案:
一個例項:
#include <sys/stat.h>
#include<stdio.h>#include<time.h>
#include<sys/types.h>
int main()
{
char txtname[100];
*txtname='005';//這句將結果轉變為字串
if(access("/root/zy/telnet/flow",0)==-1)//access函式是檢視檔案是不是存在
{
if (mkdir("/root/zy/telnet/flow",0777))//如果不存在就用mkdir函式來建立
{
printf("creat file bag failed!!!");
}
}
char pathname[100];
pathname[0]='f';
pathname[1]='l';
pathname[2]='o';
pathname[3]='w';
pathname[4]='/';
pathname[5]='/';
int i;
for(i=0;txtname[i]!='\0';i++)
{
int j=6+i;
pathname[j]=txtname[i];
}
pathname[i+6]='.'; //這幾句是加上字尾 .txt的
pathname[i+7]='t';
pathname[i+8]='x';
pathname[i+9]='t';
pathname[i+10]='\0';//最後別忘記加上這個
FILE *fp;
if((fp=fopen(pathname,"w"))==NULL)//開啟檔案 沒有就建立
{
printf("檔案還未建立!\n");
}
fprintf(fp,"建立成功");
fclose(fp);
return 0;
}
編譯一個後有警告:
CreateFile.c: In function ‘main’:
CreateFile.c:10:16: warning: multi-character character constant
CreateFile.c:10:5: warning: overflow in implicit constant conversion
修改:
char txtname[100];
*txtname='005';//這句將結果轉變為字串
改為:
char txtname[100] = “005”;
access()函式的使用:無印證
標頭檔案:unistd.h
功 能: 確定檔案或資料夾的訪問許可權。即,檢查某個檔案的存取方式,比如說是隻讀方式、只寫方式等。如果指定的存取方式有效,則函式返回0,否則函式返回-1。
用 法: int access(const char *filenpath, int mode); 或者int _access( const char *path, int mode );
引數說明:
filenpath
檔案或資料夾的路徑,當前目錄直接使用檔案或資料夾名
備註:當該引數為檔案的時候,access函式能使用mode引數所有的值,當該引數為資料夾的時候,access函式值能判斷資料夾是否存在。在WIN NT 中,所有的資料夾都有讀和寫許可權
mode
要判斷的模式
在標頭檔案unistd.h中的預定義如下:
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
#define X_OK 1 /* Test for execute permission. */
#define F_OK 0 /* Test for existence. */
具體含義如下:
R_OK 只判斷是否有讀許可權
W_OK 只判斷是否有寫許可權
X_OK 判斷是否有執行許可權
F_OK 只判斷是否存在
access函式程式範例(C語言中)
#include <stdio.h>
#include <io.h>
int file_exists(char *filename);
int main(void)
{
printf("Does NOTEXIST.FIL exist: %s\n",
file_exists("NOTEXISTS.FIL") ? "YES" : "NO");
return 0;
}
int file_exists(char *filename)
{
return (access(filename, 0) == 0);
}