Question

I've just started learning linux and C, please don't judge me strictly.

I'm trying to find a current working directory and to open file in this directory to find a specific word. It gives correct cwd if I find only cwd, but when I added while loop cwd is null.

#include <unistd.h>
#include <stdio.h>
#include <limits.h>
main(){
char *buff;
char *currentDir =getcwd(buff,PATH_MAX);

printf("Current directory: %s\n",currentDir);

FILE *file;
char *filename = "profile";
file = fopen(filename,"r");
if(file == NULL)
{
fprintf(stderr,"File %s wasn't found\n",filename);
}

while(1)
{
    char buffer[80];
    char *token;
    fgets(buffer,80,file);
    if(feof(file))
    {break;}
    else{
    *token = strtok(buffer,"=");
        if(strcmp(token,"HOME")==1);
        {
        printf("HOME token is found");
        } 
    }
free(token);
}

fclose(file);
}

The output: Current directory: (null) Segmentation fault

Was it helpful?

Solution

buff is pointing to random memory.

You might like to declare buff like so:

char buff[PATH_MAX] = "";

If on Linux then one can alternatively let getcwd() allocate the memory needed by doing so:

char * currentDir = getcwd(NULL, 0);

currentDir needs to be passed to free() when done with it, and buff is not needed then.

OTHER TIPS

Remove the line:

free(token);

token points into buffer, which is on the stack. So, no need to free it.

Another bug is:

*token = strtok(buffer,"=");

strtok() returns a char*, so this should read:

token = strtok(buffer,"=");

You should also modify your loop to:

#include <string.h>

...
char buffer[80];
while (fgets(buffer,80,file)) {
    char *token = strtok(buffer,"=");
    if (strcmp(token,"HOME") == 0);
    {
        printf("HOME token is found");
    }
...

Small function to get current directory:

void get_working_dir(void) 
{
    char buf[PATH_MAX];

    if (getcwd(buf, sizeof(buf)) == NULL) {
       fprintf(stderr, "Err.:(%d) - %s: curr. workdir\n", errno,strerror(errno));
       exit(EXIT_FAILURE);
    }

    /* print current directory */
    printf("%s\n", buf);
}

Invoke function with:

get_working_dir();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top