Reputation: 31
i am trying to create an program to generate empty files. but when it try to run the program it crashes after taking inputs from the console .
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int create(char* filename)
{
char filext[10];
printf("\nEnter File Extension :");
fgets(filext);
FILE* fp;
fp = fopen(strcat(filename,strcat(".",filext)),"w");
if(!fp)
{
return 0;
}
fclose(fp);
return 1;
}
int main(int argc , char* argv[])
{
int f;
int i;
char buffer[33];
if (argc == 3)
{
for(i = 0; i < atoi(argv[2]) ; i++)
{
f = create(strcat(argv[1],itoa(i,buffer,10)));
if(f==0)
{
printf("error in creating files . check uac!!!");
}
else{
printf("\nfile Created ...\n");
}
}
}
else{
printf("syntax Error");
}
return 0;
}
when I try to run this program I get the following output
F:\selfcreatedtools\filegen>gcc gen.c
F:\selfcreatedtools\filegen>a level 100
Enter File Extension :php
after entering the extension the program crashes. i am a beginner in c programming.
Upvotes: 0
Views: 181
Reputation: 5207
Your main problem lies in the strcat(".",filext)
part of
fp = fopen(strcat(filename,strcat(".",filext)),"w");
Try
strcat(filename, ".");
strcat(filename, filext);
fp = fopen(filename, "w");
And it might be better if the function definition header was made
int create(char filename[SIZE])
(where SIZE
is a value less than the size filename
will be) instead of int create(char* filename)
since you are using strcat()
to modify the string in the user-defined function create()
. You wouldn't want illegal memory accesses that would cause errors if the string encroaches upon the memory allotted to something else.
A similar problem is there with using strcat()
to modify the string at argv[1]
as pointed out by Jonathan Leffler for which BLUEPIXY has provided a solution in the comments.
Upvotes: 1