cdev
cdev

Reputation: 5361

read a file and remove characters using C

I am struggling with read a file and remove some characters in the line, I can remove characters any how, but the char * contain so many unknown things.

this is inside of my file. just a one line

localpath=/home/ubu/myDocs

in my code

#include <stdio.h>
#include <strings.h>

char *path;

int main()
{ 
  static const char filename[] = "pathFile";
  FILE *file = fopen ( filename, "r" );

   if ( file != NULL )
   {
      char line[512];
      while ( fgets ( line, sizeof line, file ) != NULL ) // read a line 
      {
         fputs ( line, stdout ); // write the line 
         path = strchr(line,'=') +1 ;
      }
      fclose ( file );
   }
   else
   {
      perror ( filename ); // why didn't the file open? 
   }
}

but the problem is I can't use path, as example chdir(path); is not working, but if I use like this strcpy(path,"/home/ubu/myDocs"); I can use it,

So get am idea I print the char like this

for (i=0, i < 200; i++) printf(path[i]);

in the first case I got some weird character after the("/home/ubu/myDocs") in output, but in the second case I didn't get that kind of things and it works well. I can't understand what to do, I followed so many methods in internet, but same thing happen, Please explain me what happen and give me some solution

p.s I found that in first case chdir return value is < 0, that mean path is wrong no,,,but it consists path and something useless thing

thanks

Upvotes: 0

Views: 1746

Answers (1)

rliu
rliu

Reputation: 1148

Can you add exactly what output you see from your printf()?

My best guess is that fgets() is just including extra characters. When you do an fgets() and you pass in sizeof line it will read up to 512 characters but will stop after a newline, \n, or EOF (or perhaps other characters like a carriage return, \r). In particular, if there's a newline in your file, that will get copied over in the fgets(). Try removing any extra characters at the end of the path in your file.

Edit So you have two separate problems. First is why you see garbage when you print the path. Well... that's because you print 200 characters. What do you want the other ~190 characters to be? I do not know why you don't see garbage when you use strcpy() but you haven't really shown exactly what you did. The second problem is the one that @WhozCraig pointed out. Your line goes out of scope at the end of that if block. If you call chdir() on path after that point then path points to garbage.

Upvotes: 1

Related Questions