Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   file-string proccesing c (http://www.go4expert.com/forums/file-string-proccesing-c-t23996/)

mike_ledis 26Nov2010 05:46

file-string proccesing c
 
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.

xpi0t0s 26Nov2010 13:43

Re: file-string proccesing c
 
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.

xpi0t0s 26Nov2010 13:43

Re: file-string proccesing c
 
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.

mike_ledis 26Nov2010 14:21

Re: file-string proccesing c
 
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);
}

xpi0t0s 26Nov2010 21:12

Re: file-string proccesing c
 
\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.


All times are GMT +5.5. The time now is 17:04.