C语言 C fopen 调用变量名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16425148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:17:00  来源:igfitidea点击:

C fopen call with variable name?

cfile-io

提问by Tristan V

Is there ever a circumstance where the following would work? (I'm trying to pull the value of a variable and create a file based off the text stored in the array.)

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

#include <stdio.h>

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

Thanks

谢谢

回答by

Is there ever a circumstance where the following would work?

是否有以下情况会起作用?

No.

不。



Do not make assumptions!Read the manual instead. It is really worth it.

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

char buf[0x100];
snprintf(buf, sizeof(buf), "%s.txt", random_string);
FILE *f = fopen(buf, "r");

回答by K Scott Piel

Not directly. But you could do it indirectly as follows (or anything similar to it)...

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

#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;
}

回答by awesoon

You can't assign a char variable with a string literal. You should change your code to this:

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

char a[] = "a";

Another problem is that fopenfunction gets only 2 arguments, but you're passing three.

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

回答by This isn't my real name

No, that won't work. You need an intermediate step using something like sprintf()to compose the string you want to pass to fopen().

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

回答by MOHAMED

You need to read more about fopen():

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

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

Open file

Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.

FILE * fopen ( const char * 文件名, const char * mode );

打开文件

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

And here after how to fix your code

在如何修复您的代码之后

#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;
}

回答by jarmod

No, you'd have to sprintf() to a string beforehand and then call fopen(name,mode) as usual.

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

回答by Akshayanti

I know that this thread is closed but @soon's comment suggested me a way to do it.

我知道该线程已关闭,但@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);
    }

Since fopen works with 2 arguments, we can disguise it as a single argument-

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

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

However, in case you decide to add file extension as in

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

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

it doesn't work. The system creates a file called "Dayum" which is processed as normal text file, and not csv format.

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

A note- if you can store values of extensions in one file and values of filenames in another, then join them to write a filename.extension array, that'd serve the purpose too.

注意 - 如果您可以将扩展名的值存储在一个文件中,并将文件名的值存储在另一个文件中,那么将它们连接起来编写一个 filename.extension 数组,这也可以达到目的。

回答by Patricia Cortezzi

To solve this I did:

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

#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;
}

回答by mf_

NO, fopen()returns a FILE*

否,fopen()返回一个FILE*

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

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

+

+

char a[]= "a";

字符 a[]="a";