是否有以下情况可以使用?(我正在尝试提取变量的值并根据存储在数组中的文本创建一个文件。)
#include <stdio.h>
int main()
{
char a = "a";
FILE *out;
out = fopen( "%s.txt", a, "w" );
fclose(out);
return 0;
}
谢谢
是否有以下情况可以使用?
不。
不要做假设!而是阅读手册。这真的很值得。
char buf[0x100];
snprintf(buf, sizeof(buf), "%s.txt", random_string);
FILE *f = fopen(buf, "r");
不是直接的。但是您可以按如下方式间接执行此操作(或类似的任何操作)...
#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;
}
您不能使用字符串文字分配 char 变量。您应该将代码更改为:
char a[] = "a";
另一个问题是fopen
函数只得到 2 个参数,但你传递了三个。
不,那行不通。您需要一个中间步骤,使用类似sprintf()
的方法来编写要传递给 fopen() 的字符串。
不,您必须事先将 sprintf() 转换为字符串,然后像往常一样调用 fopen(name,mode) 。
您需要阅读有关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;
}
我知道该线程已关闭,但@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 数组,这也可以达到目的。
为了解决这个问题,我做了:
#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;
}
否,fopen()
返回一个FILE*
FILE *fopen(const char *path, const char *mode);
+
字符 a[]= "a";
strcpy(a, ".txt");
fopen(a, "w");
可能会做你所要求的。