-3

我正在尝试编写一个程序来保存“X”个简单文本文件 - 但是,一旦程序运行,X 由用户确定。我似乎在网上找不到任何关于如何解决以下两件事的帮助,所以任何提示将不胜感激!

1)如果我不知道会有多少,我如何在程序开始时声明这些文本文件?

  • 到目前为止,我习惯使用:

    FILE* outfile;
    
  • 但我真正需要的是:

    FILE* outfile_0, outfile_1, outfile_2... outfile_X;
    
  • 想到的解决方案看起来像一个循环,但我知道这行不通!

    for (i=0;I<X;i++){
        FILE* outfile_i     // obviously, this just literally calls it "outfile_i" 
    }
    

2)我如何命名它们?

  • 我想称它们为简单的名称,例如“textfile_1,textfile_2”等,但我不知道如何使用:

    outfile=fopen("C:\\textfile.txt","w");
    
  • 再一次,我想也许会做一个循环(?!),但我知道这行不通:

    for(i=0;i<X;i++){
        outfile_i=fopen("C:\\textfile_i.txt","w");
    }
    

在运行程序之前绝对无法知道变量“X”是什么。

编辑:问题已解决-我不知道您可以创建“FILE *”数组,感谢您的帮助!

4

5 回答 5

1

像这样的东西应该可以工作,但需要错误处理和关闭/释放操作。

FILE **outfile = malloc(sizeof(FILE*) * X);
for(i=0;i<X;i++){
    char buffer[1024];
    sprintf(buffer, "%s_%d.txt", "textfile", i);
    outfile[i] = fopen(buffer, "w");
}
于 2014-08-20T11:21:23.187 回答
0

这应该可以帮助你。

# include <stdio.h>
# include <string.h>
int main ()
{
    char *textfile;
    int i, X;
    textfile = (char *) malloc (128 * sizeof (char));
    FILE *fptr;
    printf ("Enter the value of X: ");
    scanf ("%d", &X);
    for (i=1 ; i<=X ; i++)
    { 
        sprintf(textfile, "textfile_%d.txt", i);
        fptr = fopen (textfile, "w");
        fclose (fptr);
    }
    return 0;
}
于 2014-08-20T11:27:33.130 回答
0

尝试这个-

char buffer[100];
FILE* outfile[X];
for(i=0;i<X;i++){
snprintf(buffer,100,"C:\\textfile_%d.txt",i);

outfile[X]=fopen(buffer,"w");
}
于 2014-08-20T11:24:29.770 回答
0

您必须将变量存储在某个结构(数组、列表...)中并在内存中创建一些字符串。例如 :

#include <stdio.h>

#define X 5

int main() {
  FILE* outfiles[X];
  unsigned short i;
  char fn[32];
  for (i = 0; i < X; ++i) {
    sprintf(fn, "outfile_%u", i);
    outfiles[i] = fopen(fn, "w");
  }
}
于 2014-08-20T11:22:22.450 回答
0

您必须将所有FILE *变量放在一个数组中。我会做:

char filename[80];
char number[10];

/* Allocate our array */
FILE ** files = malloc((sizeof(FILE *) * X) + 1); /* We allocate a size of X+1 because we'll have X elements + a last NULL element. */

/* Populate our array */
for (int i = 0; i < X; i++)
{
    strcpy(filename,"C:\\textfile_");
    itoa(i, number, 10); /* Here 10 means we use decimal base to convert the integral value. */
    strcat(filename, number);
    strcat(filename, ".txt");

    files[i] = fopen(filename, "w");
}
files[i] = NULL; /* Here we set the last element of our array to NULL (so when we iterate over it we can stop when we encounter NULL). */

然后您可以像这样访问所有文件:

for (int i = 0; files[i] != NULL; i++)
{
    FILE * current = files[i];
    /* Do something with "current" here. */
}

PS:需要进行一些安全检查:
malloc→ 验证它不会返回NULL
itoa→ 验证输出字符串是否有效。
fopen→ 验证文件是否已打开。

于 2014-08-20T11:29:26.923 回答