Home › Forums › C Programming › need help in adding a charecter to the file name › Re: Re: need help in adding a charecter to the file name
February 25, 2010 at 8:58 am
#3610
LenoraRamsey
Participant
Try this code for you requirement It will solve you problem.
As you want it will check for abcd if it is there it will check for abcd1 file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | <br /> #include<stdio.h><br /> #include<string.h><br /> #include<stdlib.h><br /> #include<limits.h><br /> <br /> char *reverse(char s[])<br /> {<br /> int c,i,j;<br /> <br /> for(i=0,j=strlen(s)-1;i<j;i++,j--)<br /> {<br /> c=s<i>;<br /> s</i><i>=s[j];<br /> s[j]=c;<br /> }<br /> return s;<br /> }<br /> <br /> <br /> <br /> char *itoa(int n)<br /> {<br /> char s[100];<br /> int i,sign,ind=0,mod,w=0;<br /> if((sign=n)<0){<br /> if(sign<=INT_MIN)<br /> {<br /> mod=-(n%10);<br /> n=n/10;<br /> ind=1;<br /> }<br /> n=-n;<br /> }<br /> i=0;<br /> do<br /> {<br /> if(ind==1)<br /> {<br /> s[0]=mod+'0';<br /> i++;<br /> ind=0;<br /> }<br /> s[i++]=n%10+'0';<br /> <br /> }while((n/=10)>0);<br /> s</i><i>='';<br /> return (reverse(s));<br /> }<br /> <br /> int exists(const char *filename)<br /> {<br /> FILE *f = fopen(filename, "r");<br /> if (!f) return 0;<br /> fclose(f);<br /> return 1;<br /> }<br /> <br /> int main ( )<br /> {<br /> char str [1024];<br /> strcpy(str,"abcd");<br /> int num = 0;<br /> int created = 0;<br /> while(created == 0)<br /> {<br /> num++;<br /> if(exists(str))<br /> {<br /> char numb[100];<br /> strcpy(str,"abcd");<br /> strcpy(numb,"");<br /> strcpy(numb,itoa(num));<br /> strcat(str,numb);<br /> }<br /> else<br /> {<br /> FILE *f=fopen(str,"w");<br /> printf("%s file createdn",str);<br /> created=1;<br /> fclose(f);<br /> }<br /> }<br /> return 0 ;<br /> }<br /> </i> |