-
pointer problem
I am trying to read a file into a single array. For some reason, I cannot get a pointer, s1, to point to the beginning of the array. Here is my code:
Code:
#include<stdio.h>
#include<string.h>
#define BUFFER_SIZE 30
#define BIG_BUFFER 1024
#define TRUNCATE_BUF 100
int main(void)
{
int i = 0 ;
char file_string_buf[BIG_BUFFER] ;
char *s1 = file_string_buf ;
char *s2 = "cpu" ;
char truncate_string_buf[TRUNCATE_BUF] ;
FILE * infile ;
FILE * outfile ;
infile = fopen("/proc/cpuinfo", "r" );
outfile = fopen("cpuinfo.txt", "w" );
fprintf( outfile, "\n" ) ;
/*s1 = file_string_buf ;*/
while (fgets( file_string_buf, BIG_BUFFER, infile) != NULL )
printf("%s", s1 ) ;
/* fprintf(outfile, "%s", file_string_buf ) ;*/
s1 = file_string_buf ; /*
printf("s2 = %s\n", s2) ;
printf("s1 = %s\n", s1 ) ;
printf("\ncpuinfo.txt created\n" ) ;
printf("\n%s\n", strstr(s1,s2)) ;
fclose(infile) ;
fclose(outfile) ;
return(0) ;
}
As you can see, the while loop pulls the file info into a buffer called file_string_buf . I also assign s1 to point to file_string_buf at the beginning and after the file is read in. What's the problem??? Do I need to reset the file_string_buf pointer??? I don't know.
Thanks
-
Are you sure the files are being opened successfully? Check the return value from fopen() isn't NULL.
Also check that that opened comment (/*) on line 31(ish) of your post is a typo and is closed or not in your actual code.
Try simplifiying your code a little bit for now. Take out all the output file stuff and just see if you can get the while loop bit working. eg:
Code:
#include<stdio.h>
#include<string.h>
#define BIG_BUFFER 1024
int main(void)
{
int i = 0 ;
char file_string_buf[BIG_BUFFER] ;
char *s1 = file_string_buf ;
char *s2 = "cpu" ;
FILE * infile ;
if ((infile = fopen("/proc/cpuinfo", "r" )) == NULL)
{
printf("error opening file\n");
exit(EXIT_FAILURE);
}
while (fgets( file_string_buf, BIG_BUFFER, infile) != NULL )
printf("%s", s1 ) ;
fclose(infile) ;
return(0) ;
}
And move on from there...
Good luck!
-
we'll give it a whirl
Thanks, I did notice the typo... It has not seemed to have mattered, because the following statements execute...
Also, DavT, the goal of the code is to get s1 to point to the beginning of the array... Do I have to assign s1 to file_string_buf after the file is read in OR is it okay to establish the pointer at the beginning of the code?
Thanks
I will continue to debug.
-
No, its okay to set s1 = file_string_buf at the begining since file_string_buf doesn't move in memory after a fgets().
I tested the code that I posted and it works as I would expect (I did use a different file name though) and since it uses the 'printf("%s", s1 )' statement it does show that s1 points to the start of the array.
I still think that the file is not being opened properly...
-
great
Thanks, again DavT.
I am still reworking the code. By the way, I am working in Mandrake LINUX 7.0.
I will review your code post at once...
Thanks again