此程序不会创建两个以上的空文件。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int create(char filename[])
{
char filext[10+1]=".";
printf("\nEnter File Extension :");
scanf("%9s",filext+1);
FILE* fp;
strcat(filename, filext);
fp = fopen(filename,"w");
if(!fp)
{
return 0;
}
fclose(fp);
return 1;
}
int main(int argc , char* argv[])
{
int f;
int i;
char* j;
char buffer[33];
char filename[100];
if (argc == 3)
{
for(i = 0; i < atoi(argv[2]) ; i++)
{
j = itoa(i,buffer,10);
strcpy(filename,strcat(argv[1],j));
f = create(filename);
if(f==0)
{
printf("error in creating files . check uac!!!");
}
else{
printf("\nfile Created ...\n");
}
}
}
else{
printf("syntax Error");
}
return 0;
}
当我尝试执行该文件时,我得到以下输出。
F:\selfcreatedtools\filegen>gcc gen.c
F:\selfcreatedtools\filegen>a wander 4
Enter File Extension :php
file Created ...
Enter File Extension :mag
file Created ...
F:\selfcreatedtools\filegen>
当我在命令行中传递argv[2]
= 4时。根据程序循环必须迭代4次。并提供4个文件作为输出。但我的程序会生成2个文件,然后循环停止迭代。
感谢您的解决方案。我是初学者。
答案 0 :(得分:1)
这是一个没有提示扩展的解决方案 - 您可以在命令行上提供它。它使用我的错误报告功能,stderr.c
和stderr.h
#include "stderr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int create(const char *base, int numlen, int number, const char *dot, const char *extn)
{
int rc = 0;
char filename[1024];
snprintf(filename, sizeof(filename), "%s%.*d%s%s", base, numlen, number, dot, extn);
FILE *fp = fopen(filename, "w");
if (fp == 0)
{
err_sysrem("failed to create file '%s': ", filename);
rc = -1;
}
else
fclose(fp);
return rc;
}
int main(int argc, char **argv)
{
err_setarg0(argv[0]);
if (argc < 3 || argc > 4)
err_usage("base number [ext]");
char *base = argv[1];
int number = atoi(argv[2]);
const char *dot = ".";
char *extn = argv[3];
if (extn == 0)
{
dot = "";
extn = "";
}
if (*extn == '.')
dot = "";
char buffer[32];
int numlen = snprintf(buffer, sizeof(buffer), "%d", number - 1);
int rc = EXIT_SUCCESS;
for (int i = 0; i < number; i++)
{
if (create(base, numlen, i, dot, extn) != 0)
rc = EXIT_FAILURE;
}
return rc;
}
提供。
gen29
它使用https://github.com/jleffler/soq/tree/master/src/libsoq来管理字符串连接。
示例运行(程序名为$ gen29 base 10
created: [base0]
created: [base1]
created: [base2]
created: [base3]
created: [base4]
created: [base5]
created: [base6]
created: [base7]
created: [base8]
created: [base9]
$ gen29 base 10 .ext
created: [base0.ext]
created: [base1.ext]
created: [base2.ext]
created: [base3.ext]
created: [base4.ext]
created: [base5.ext]
created: [base6.ext]
created: [base7.ext]
created: [base8.ext]
created: [base9.ext]
$ gen29 base 13 xtn
created: [base00.xtn]
created: [base01.xtn]
created: [base02.xtn]
created: [base03.xtn]
created: [base04.xtn]
created: [base05.xtn]
created: [base06.xtn]
created: [base07.xtn]
created: [base08.xtn]
created: [base09.xtn]
created: [base10.xtn]
created: [base11.xtn]
created: [base12.xtn]
$
):
:
如果你真的想在文件创建中做提示,请成为我的访客并进行修改,但是IMO这样的程序没有那些没有提示的程序。