0

I would like to open a directory using opendir but am seeing something unexpected. opendir works for the string returned from getcwd but not the string from my helper function read_cwd, even though the strings appear to be equal.

If I print the strings, both print /Users/gwg/x, which is the current working directory.

Here is my code:

char real_cwd[255];
getcwd(real_cwd, sizeof(real_cwd));

/* This reads a virtual working directory from a file */
char virt_cwd[255];
read_cwd(virt_cwd);

/* This prints "1" */
printf("%d\n", strcmp(real_cwd, virt_cwd) != 0);

/* This works for real_cwd but not virt_cwd */
DIR *d = opendir(/* real_cwd | virt_cwd */);

Here is the code for read_cwd:

char *read_cwd(char *cwd_buff)
{
    FILE *f = fopen(X_PATH_FILE, "r");
    fgets(cwd_buff, 80, f);
    printf("Read cwd %s\n", cwd_buff);
    fclose(f);
    return cwd_buff;
}
jds
  • 7,910
  • 11
  • 63
  • 101

3 Answers3

3

The function fgets includes the final newline in the buffer — so the second string is actually "/Users/gwg/x\n".

The simplest (but not necessarily the cleanest) way to solve this issue is to overwrite the newline with a '\0': add the following at the end of the function read_cwd:

n = strlen(cwd_buff);
if(n > 0 && cwd_buff[n - 1] == '\n')
    cwd_buff[n - 1] = '\0';
jch
  • 5,382
  • 22
  • 41
  • [`strlen()`](http://stackoverflow.com/a/27729970/2410359) (like this answer) and [`strchr()`](http://stackoverflow.com/a/2693826/2410359), IMO, are the 2 best clean ways to remove `'\n'` after `fgets()`. – chux - Reinstate Monica Jan 05 '15 at 00:39
1

fgets() includes the newline.

Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. — http://en.cppreference.com/w/c/io/fgets


You should trim the white space on both ends of the string when reading input like this.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
1

From the fgets man page:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.

You need to remove the newline character from the string you are reading in.

Tony
  • 1,645
  • 1
  • 10
  • 13