Hello i am trying to create a programm that reads a line of a text file into a var. After that the line is being used as the directory argument into an fopen() procedure to open and reads from another file. Here is my program. main() { FILE *cfPtr1,*cfPtr2; int g1,f; int i; char sizeLineInput1[512],sizeLineInput2[512],a[512],b; cfPtr2=fopen("mike2.txt","r");// I open the first file fgets(sizeLineInput2, 512, cfPtr2);//I get the first line of my text file into my variable; cfPtr1=fopen( sizeLineInput2,"r");//I use the variable as directory to fopen() fgets(a, 512, cfPtr1);//i am trying to read from the file that i openened printf("%s",a); scanf("%s",b); } Sorry for the noob question.
What do the files contain? Have you tried displaying intermediate results? Have you checked that trying to open, say, foo.txt\n correctly opens foo.txt? fgets includes the end of line character so this could throw the program off. You don't have any error handling, I see. fopen returns NULL if the file couldn't be opened (and sets errno so you can see what the error was) so it might be an idea to check for both of those.
Correction: fgets includes the end of line character IF the buffer was big enough for the data. That's how you can tell if the buffer was too small.
I solved it thank you! The problem was that i need an end of line character(\0) to the end of my string array so that fopen() can work. In case you are intersted the new code is: main() { FILE *cfPtr1,*cfPtr2; int g1,f; int i; char sizeLineInput1[512],sizeLineInput2[512],a[512],b; cfPtr2=fopen("mike2.txt","r");// I open the first file fgets(sizeLineInput2, 512, cfPtr2);//I get the first line of my text file into my variable; if (sizeLineInput2[strlen(sizeLineInput2)-1]=='\n') sizeLineInput2[strlen(sizeLineInput2)-1]='\0'; cfPtr1=fopen( sizeLineInput2,"r");//I use the variable as directory to fopen() fgets(a, 512, cfPtr1);//i am trying to read from the file that i openened printf("%s",a); scanf("%s",b); }
\0 is the NULL terminator that must be present at the end of C strings. It is not an end of line character. End of line is \n, and is presumably why the fopen didn't work, i.e. it was trying to open foo.txt\n instead of foo.txt[\0]. fgets probably returned foo.txt\n\0.