2013-03-12 80 views
-1

我正在使用簡單的'C'代碼來執行以下操作:C中的文件操作

1)從.txt文件讀取。

2)基於.txt文件中的字符串,將創建一個目錄。

我不能執行第2步,因爲我不清楚類型轉換。

這裏是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <direct.h> 

int main() 
{ 
    char ch, file_name[25]; 
    FILE *fp; 

    //printf("Enter the name of file you wish to see\n"); 
    //gets(file_name); 

    fp = fopen("input.txt","r"); // read mode 

    if(fp == NULL) 
    { 
     perror("Error while opening the file.\n"); 
     exit(EXIT_FAILURE); 
    } 

    printf("The contents of %s file are :\n", file_name); 

    while((ch = fgetc(fp)) != EOF) 
     printf("%c",ch); 

    if(_mkdir(ch) == 0) 
    { 
     printf("Directory successfully created\n"); 
     printf("\n"); 
    } 
    fclose(fp); 
    return 0; 
} 

以下是錯誤:

*error #2140: Type error in argument 1 to '_mkdir'; expected 'const char *' but found 'char'.* 
+1

我對你感到困惑......「mkdir」需要一個字符串,而你給它一個字符有點困惑。編譯器在說同樣的事情... – Mike 2013-03-12 12:39:02

回答

3

是的,編譯器是正確的。

您正在傳遞字符c_mkdir而不是字符串。

你應該從文件中讀取字符串,並將其存儲到file_name(我想你忘記了),然後

_mkdir(file_name); 

見下文:

#include <stdio.h> 
#include <stdlib.h> 
#include <direct.h> 


int main() 
{ 
    char file_name[25]; 
    FILE *fp; 

    fp = fopen("input.txt", "r"); // read mode 

    if (fp == NULL) 
    { 
     perror("Error while opening the file.\n"); 
     exit(EXIT_FAILURE); 
    } 

    fgets(file_name, 25, fp); 

    _mkdir(file_name); 

    fclose(fp); 
    return 0; 
} 
+0

好的,我加了這個,仍然不起作用 'while((ch = fgetc(fp))!= EOF) printf(「%c」,ch); \t char str [25] = ch;如果(_mkdir(str)== 0) { printf(「成功創建的目錄\ n」); }' – highlander141 2013-03-12 12:52:12

+1

@ highlander141,爲什麼不使用'fgets()'從文件讀取? – 2013-03-12 12:56:11

2

這是因爲你只能有一個char(在cfgetc代表char),而_mkdir想要一個字符串(即char *)。

您應該使用fgets來讀取輸入。

1

如果你不想用fgets,然後你可以使用這個。

#include <stdio.h> 
#include <stdlib.h> 
#include <direct.h> 
int main() 
{ 
char file_name[25]; 
String str; 
FILE *fp; 
char ch; 
int i=0; 

fp = fopen("input.txt", "r"); // read mode 

if (fp == NULL) 
{ 
    perror("Error while opening the file.\n"); 
    exit(EXIT_FAILURE); 
} 
while((ch = fgetc(fp)) != EOF){ 
    printf("%c",ch); 
    file_name[i]; 
    i++ 
} 
str=file_name; 

_mkdir(str); 

fclose(fp); 
return 0; 
}