【问题标题】:Chose To write a File to a Specific Directory [duplicate]选择将文件写入特定目录[重复]
【发布时间】:2016-01-20 12:04:42
【问题描述】:

所以我正在尝试创建一个文件并将其保存到所需的目录。

例如:用户输入:

目录? 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");

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您不能使用 C 中的 + 运算符连接字符串。为此请使用 strcat 或任何其他适当的函数。
  • 正如@FUZxxl 所说,您将不得不使用strcat 来连接字符串。
  • 您至少应该报告您遇到了哪种错误,即在编译时(哪个错误?)或运行时(哪个错误行为?)

标签: c fopen c-strings


【解决方案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' 指出一些错误。

【讨论】:

  • 您应该初始化file_name[0] = '\0' 以确保它是一个有效的空字符串。或者使用strcpy 完全复制第一个字符串。
  • @Lærne,好吧,我会做的。
【解决方案2】:

几个问题:

  • 您必须使用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");

【讨论】:

【解决方案3】:

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

你最好使用strcat:

char fname[200+200];

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

out_file = fopen(fname, "w");

* 虽然你可以添加指针。在您的情况下,它没有达到您的预期。

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 2019-06-16
    • 2020-10-05
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多