6

是否有以下情况可以使用?(我正在尝试提取变量的值并根据存储在数组中的文本创建一个文件。)

#include <stdio.h>

int main()
{
    char a = "a"; 
    FILE *out;
    out = fopen( "%s.txt", a, "w" );
    fclose(out);
    return 0;
}

谢谢

4

10 回答 10

13

是否有以下情况可以使用?

不。


不要做假设!而是阅读手册。这真的很值得。

char buf[0x100];
snprintf(buf, sizeof(buf), "%s.txt", random_string);
FILE *f = fopen(buf, "r");
于 2013-05-07T17:36:07.913 回答
7

不是直接的。但是您可以按如下方式间接执行此操作(或类似的任何操作)...

#include <stdio.h>

int main()
{
    char* a = "a"; 
    char* extension = ".txt";
    char fileSpec[strlen(a)+strlen(extension)+1];
    FILE *out;

    snprintf( fileSpec, sizeof( fileSpec ), "%s%s", a, extension );

    out = fopen( fileSpec, "w" );
    fclose(out);
    return 0;
}
于 2013-05-07T17:36:11.143 回答
1

您不能使用字符串文字分配 char 变量。您应该将代码更改为:

char a[] = "a";

另一个问题是fopen函数只得到 2 个参数,但你传递了三个。

于 2013-05-07T17:35:10.450 回答
1

不,那行不通。您需要一个中间步骤,使用类似sprintf()的方法来编写要传递给 fopen() 的字符串。

于 2013-05-07T17:36:11.727 回答
0

不,您必须事先将 sprintf() 转换为字符串,然后像往常一样调用 fopen(name,mode) 。

于 2013-05-07T17:41:58.497 回答
0

您需要阅读有关fopen()的更多信息:

文件* fopen(常量字符*文件名,常量字符*模式);

打开文件

打开其名称在参数文件名中指定的文件,并将其与一个流相关联,该流可以在以后的操作中通过返回的 FILE 指针来标识。

在如何修复代码之后

#include <stdio.h>

main(){

char a = 'a';
char filename[64];

FILE *out;
sprintf(filename, "%c.txt", a)

out = fopen( filename, "w");

fclose(out);

return 0;
}
于 2013-05-07T17:38:07.987 回答
0

我知道该线程已关闭,但@soon 的评论为我提供了一种方法。

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

    void main()
    {
      FILE *fs;
      char c[]="Dayum.csv";
      fs = fopen( ("%s", c),"a");
      if (fs == NULL)
        printf("Couldn't open file\n");
        for (int i=0; i<5; i++)
          for (int j=0; j<5; j++)
            fprintf(fs, "%lf,%lf\n",i,j);
    fclose(fs);
    }

由于 fopen 使用 2 个参数,我们可以将其伪装成单个参数 -

fs = fopen( ("%s", c), "a" )

但是,如果您决定添加文件扩展名,如

char c[]="Dayum";
fs = fopen( ("%s.csv",c), "a")

它不起作用。系统会创建一个名为“Dayum”的文件,该文件被处理为普通文本文件,而不是 csv 格式。

注意-如果您可以将扩展名的值存储在一个文件中,而将文件名的值存储在另一个文件中,则将它们加入以编写 filename.extension 数组,这也可以达到目的。

于 2017-10-29T03:36:42.827 回答
0

为了解决这个问题,我做了:

#include <string.h>

int main()
{
    char fileName = "a"; 
    FILE *out;

    char fileToOpen[strlen(fileName) + 5]; 
    // strlen(fileName)+5 because it's the length of the file + length of ".txt" + char null

    strcpy(fileToOpen, fileName); 
    // Copying the file name to the variable that will open the file

    strcat(fileToOpen, ".txt"); 
    // appending the extension of the file

    out = fopen( fileToOpen, "w" ); 
    // opening the file with a variable name

    if(out == NULL)
    {
        perror("Error: ");
        exit(EXIT_FAILURE);
    }
    fclose(out);

    return EXIT_SUCCESS;
}
于 2019-09-17T15:51:55.003 回答
-2

否,fopen()返回一个FILE*

FILE *fopen(const char *path, const char *mode);

+

字符 a[]= "a";

于 2013-05-07T17:35:40.147 回答
-2
strcpy(a, ".txt");
fopen(a, "w");

可能会做你所要求的。

于 2020-09-09T15:40:16.563 回答