Sunday, July 12, 2009

Need help with my c program?

i need my program to read in a file reverse it then write the file out.


i got the reverse correct but its not working.


my errors are:


n.c:12: warning: passing argument 1 of 'fopen' from incompatible pointer type


n.c:21: warning: passing argument 1 of 'fopen' from incompatible pointer type


n.c:22: warning: passing argument 1 of 'fputs' from incompatible pointer type


n.c:22: error: too few arguments to function 'fputs'





#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;


#include %26lt;ctype.h%26gt;


int main() {


char string[256];


char*filename[256];


char*outfilen[256];


char c;


int len;


FILE * infile=0;


FILE * outfile;


infile=fopen(filename,"r");


fgets(string, sizeof string, stdin);


len = (strlen(string) - 1);





printf("Reverse string:\n");


for(; len %26gt;= 0; len--)


printf("%c",string[len]);





printf("\n");


outfile=fopen(outfilen,"w");


fputs(outfile);


fclose(infile);


fclose(outfile);


}

Need help with my c program?
fputs() takes two arguments. You need to pass in "string" as well as the file, like this:





fputs(string, outfile);
Reply:Based on my experience in Java,


I think the cause of the warning is that you defined a pointer for the variable (filename)


which I quite don't understand why..


try do declare it like that : char filename[256]


About the Error:


here is the right format for the function fputs:


int fputs ( const char * str, FILE * stream );


All what you have to do is to provide the string you've defined..something like that :


fputs(string, outfile);





-cheers
Reply:A lot of issues here. This version compiles with gcc.


#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;


#include %26lt;ctype.h%26gt;


int main() {


char string[256];


char filename[256];


char outfilen[256];


char c;


int len;


FILE * infile=0;


FILE * outfile;





infile=fopen(filename,"r");


fgets(string, sizeof(string), stdin);


len = (strlen(string) - 1);





printf("Reverse string:\n");


for(; len %26gt;= 0; len--)


printf("%c",string[len]);





printf("\n");


outfile=fopen(outfilen,"w");


fputs(string,outfile);


fclose(infile);


fclose(outfile);


}





Note, the arrays are now arrays of 256, not pointers to arrays of 256.





in fgets, sizeof is a function, which means it on't compile unless you write sizeof(string) not sizeof string.








And of course, you reverse the string to stdout, but not to the outfile. That I haven't done anything about fixing. I wouldn't initialize infile when you declare it, incidently. Since you are going to reassign it it might help keep things straight if you assign it down below in the functions. Keep initializing in declarations to consts. That's just preference.


No comments:

Post a Comment