如何在 c 中使用数组打开文件
how do I open files using an array in c
我想打开名为 ex1, ex2, ex3 ...exn
等的文件。
现在当我输入 n
的值时,n=1, ex1
将被打开
因为,n=2, ex2
文件将被打开,然后我将从其中读取或写入我的 C 程序输出数组。
文件名可以字符串形式给出吗?
由于我是编程新手,请帮助我解决这个问题。
通常当您打开一个文件时,您使用函数fopen
fp = fopen ("file.txt", "w+");
if (fp == NULL)
{
exit(1); // Or you can raise some error code and return if this code is in a function.
}
// Process the file
现在在你的情况下,你需要操作文件名。所以你可以为此取一个 C 字符串。
char filename[10];
// N is set from code above
sprintf(filename,"ex%d",N);
fp = fopen (filename, "w+");
// Further behaviour is same
我想打开名为 ex1, ex2, ex3 ...exn
等的文件。
现在当我输入 n
的值时,n=1, ex1
将被打开
因为,n=2, ex2
文件将被打开,然后我将从其中读取或写入我的 C 程序输出数组。
文件名可以字符串形式给出吗?
由于我是编程新手,请帮助我解决这个问题。
通常当您打开一个文件时,您使用函数fopen
fp = fopen ("file.txt", "w+");
if (fp == NULL)
{
exit(1); // Or you can raise some error code and return if this code is in a function.
}
// Process the file
现在在你的情况下,你需要操作文件名。所以你可以为此取一个 C 字符串。
char filename[10];
// N is set from code above
sprintf(filename,"ex%d",N);
fp = fopen (filename, "w+");
// Further behaviour is same