2016-01-20 76 views
-3

所以我试图创建一个文件并将其保存到所需的目录。选择将文件写入特定目录

例如:用户输入:

目录? c:\user\sample\

名称? hello.txt

这是我到目前为止已经试过:

char str[200],str2[200]; 
FILE * out_file; 
fgets(str,sizeof str,out_file); 
fgets(str2,sizeof str2,out_file); 
out_file = fopen(str+str2,"w"); 

有人可以帮我这个问题?

+1

您不能在C中使用'+'运算符连接字符串。为此使用'strcat'或任何其他适当的函数。 – fuz

+0

因为,@FUZxxl说,你将不得不使用'strcat'来连接字符串。 –

+5

阅读本文[如何连接C中的2个字符串?](http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c) –

回答

0

你不能在C中连接这样的字符串! *

你最好使用strcat

char fname[200+200]; 

strcat(fname, str); 
strcat(fname, str2); 

out_file = fopen(fname, "w"); 

*虽然你被允许添加指针。在你的情况下,它不符合你的期望。

1

的几个问题:

  • 你将不得不使用strcat()来连接字符串。

  • 这里您在阅读out_file之前打开它。

    fgets(str,sizeof str,out_file); 
    fgets(str2,sizeof str2,out_file); 
    

一个简单的例子(做检查没有错误):

char str[200], str2[200]; 
char fname[400]; 
FILE *out_file; 

printf("\nEnter path: "); 
scanf("%199s", str); 
printf("\nEnter filename: "); 
scanf("%199s", str2); 

strcpy(fname, str); 
strcat(fname, str2); 

out_file = fopen(fname, "w"); 

或者更短的方式:

char str[400],str2[200]; 
FILE * out_file; 

printf("\nEnter path: "); 
scanf("%199s", str); 
printf("\nEnter filename: "); 
scanf("%199s", str2); 

strcat(str, str2); 

out_file = fopen(str, "r"); 
+0

千万不要使用'gets'。使用'fgets'。 –

+0

'gets'非常危险。看看这个:[为什么gets功能如此危险以至于不应该使用?](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it -should-不待使用)。 –

+0

@AshishAhuja - 是的,但希望保持简短的样例(换行符等) - 使用'scanf()'代替。 –

1

How to concatenate 2 strings in C?。您也可以使用strcat

检出this教程。

在这样的一个例子是:

/* Example using strcat by TechOnTheNet.com */ 

#include <stdio.h> 
#include <string.h> 

int main(int argc, const char * argv[]) 
{ 
    /* Define a temporary variable */ 
    char example[100]; 

    /* Copy the first string into the variable */ 
    strcpy(example, "TechOnTheNet.com "); 

    /* Concatenate the following two strings to the end of the first one */ 
    strcat(example, "is over 10 "); 
    strcat(example, "years old."); 

    /* Display the concatenated strings */ 
    printf("%s\n", example); 

    return 0; 
} 

你的情况,那就是:

char file_name[200 + 200]; 
file_name [0] = '\0'     // To make sure that it's a valid string. 

strcpy (file_name, str);    // Concatenate `str` and `file_name` 
strcat(file_name, str2);    // Concatenate `str2` and `file_name` 

out_file = fopen(file_name, "w");  // Open the file. 

而且,这要归功于指出了一些错误 'laerne'。

+1

您应该初始化'file_name [0] ='\ 0'',以确保它是一个有效的空字符串。或者用“strcpy”完全复制第一个字符串。 –

+0

@Lærne,好的,我会做的。 –