创建一个程序,该程序要求用户输入一个名称,并创建10个使用C序列化名称的文件

创建一个程序,该程序要求用户输入一个名称,并创建10个使用C序列化名称的文件,c,string,file,C,String,File,我正在尝试解决文件处理问题,但我想不出一种方法来解决这个问题。任何帮助都将不胜感激! 需要这样的东西: #include<stdio.h> int main() { char string[10]; FILE *fp1; printf("Enter the string"); scanf("%s", string); fp1 = fopen(string, "w"); /----

我正在尝试解决文件处理问题,但我想不出一种方法来解决这个问题。任何帮助都将不胜感激! 需要这样的东西:

#include<stdio.h>
int main()
{
        char string[10];
        FILE *fp1;

        printf("Enter the string");
        scanf("%s", string);

        fp1 = fopen(string, "w");


        /---- 


        fclose(fp1);
        return 0;
}
输出:

Created Test1.txt, Test2.txt, Test3.txt, .... Test10.txt

就这么做吧

#include<stdio.h>
#include <assert.h>

#define N 10

int main()
{
  assert((N >= 0) && (N <= 999)); /* check the value of N if it is changed */

  char base[10]; /* the base name of the files */
  FILE *fp[N]; /* to save the file descriptors */

  printf("Enter the base name:");
  if (scanf("%9s", base) != 1)
    // EOF
    return -1;

  char fn[sizeof(base) + 7]; /* will contains the name of the files */

  for (int i = 0; i != N; ++i) {
    sprintf(fn, "%s%d.txt", base, i+1);
    if ((fp[i] = fopen(fn, "w")) == 0)
      printf("cannot open %s\n", fn);
  }

  /* ... */

  for (int i = 0; i != N; ++i) {
    if (fp[i] != NULL)
      fclose(fp[i]);
  }

  return 0;
}

在执行之前,echo aze*生成aze*,因为没有名称以aze开头的文件,在执行之后,aze*表示创建的文件是预期的

您在哪里遇到问题?获取用户输入?创建文件名?创建文件?你尝试过什么?发布您迄今为止的尝试。请向我们展示您尝试了什么以及失败的原因。请阅读第页!!另外:要创建文本文件,只需查看在w模式下打开的fopen函数。这将使用您在第一条注释中提到的指定名称打开新文件,请参阅。字符文件名[256];SprintfielName,%s%d.txt,用户输入,用户编号;这似乎确实奏效了。。但是你能告诉我我的代码有什么问题吗?我似乎只是在用一个随机名称创建一个文件:forint I=0;i@NeXT在sprintffn中,s%d,string,i您错过了一个%,必须是sprintffn,%s%d,string,i,因为您将字符串设置为“s”,然后字符串地址的一部分谢谢,它似乎起作用了@接下来欢迎大家,快乐编码
Created Test1.txt, Test2.txt, Test3.txt, .... Test10.txt
#include<stdio.h>
#include <assert.h>

#define N 10

int main()
{
  assert((N >= 0) && (N <= 999)); /* check the value of N if it is changed */

  char base[10]; /* the base name of the files */
  FILE *fp[N]; /* to save the file descriptors */

  printf("Enter the base name:");
  if (scanf("%9s", base) != 1)
    // EOF
    return -1;

  char fn[sizeof(base) + 7]; /* will contains the name of the files */

  for (int i = 0; i != N; ++i) {
    sprintf(fn, "%s%d.txt", base, i+1);
    if ((fp[i] = fopen(fn, "w")) == 0)
      printf("cannot open %s\n", fn);
  }

  /* ... */

  for (int i = 0; i != N; ++i) {
    if (fp[i] != NULL)
      fclose(fp[i]);
  }

  return 0;
}
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra f.c
pi@raspberrypi:/tmp $ echo aze*
aze*
pi@raspberrypi:/tmp $ ./a.out
Enter the base name:aze
pi@raspberrypi:/tmp $ echo aze*
aze10.txt aze1.txt aze2.txt aze3.txt aze4.txt aze5.txt aze6.txt aze7.txt aze8.txt aze9.txt
pi@raspberrypi:/tmp $