Question

when i use open() as

int ff=open("/home/user/desktop/bla/test",O_RDONLY);

it works fine.

but when i use a string as the (same path stored in a string) path it doesn't work.

int ff=open(string,O_RDONLY);

why is this?

this is my whole code. i'm confused. i know it should work. but i doesn't. i can't find the bug.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>

void bla(char *);
int main(void)
{
// int i;
FILE * fp=fopen("path","r");
char line[256];

while( fgets(line,255,fp)!=NULL){

bla(line);

 }

return 0;
}


void bla(char * line){

int status;
printf("%s",line);


pid_t pid=fork();

char string[256];
if(pid==0){

    pid=wait(&status);

    int ff=open(line,O_RDONLY);

    if(ff<0){
        printf("\topen error!\n\n");
    return;}

    int ret=read(ff,string,255);

    if(ret<0){
        printf("read error!\n");
    return;}

    printf("%s",string);
close(ff);

exit(0);


}   
if (pid>0){
        return;
}
 }

in bla function, if i replace 'line' with the path, it works. i used a printf to make sure. path is the same (it seems the same).

Was it helpful?

Solution

I call shenanigans :-)

Obviously, if string were exactly the same value as your string literal, and all others things remained the same, it would work fine.

So, if all other things are the same, string is obviously not set to the value you think it is, to wit "/home/user/desktop/bla/test".

My advice would be to print it out (along with an error string) to be sure, something like:

fprintf (stderr, "DEBUG: string is [%s]\n", string);
int ff = open (string, O_RDONLY);
if (ff < 0)
    perror ("Could not open file");

And, now that you've posted the code, your problem is obvious: fgets() does not remove the trailing newline so, were you to add the code I proposed above, you would see:

DEBUG: string is [/home/user/desktop/bla/test
]

and deduce the problem.

A quick way to fix this is to remove the newline yourself, with something like:

while (fgets (line, 255, fp) != NULL) {
    size_t ln = strlen (line);             // Add these
    if ((ln > 0) && (line[ln-1] == '\n'))  //   three
        line[ln-1] = '\0';                 //   lines.
    bla (line);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top