jenny
jenny

Reputation: 520

Setting date and time for a file name using C

I found an example to set date and time for a file. Can anyone explain what this loop:

for (; *p; ++p)
{
    if (*p == ' ')
          *p = '_';
}

...means?

/* ctime example */
    #include <stdio.h>      /* printf */
    #include <time.h>       /* time_t, time, ctime */

    int main ()
    {
      time_t rawtime;
      char buffer [255];

      time (&rawtime);
      sprintf(buffer,"/var/log/SA_TEST_%s",ctime(&rawtime) );
    // Lets convert space to _ in

    char *p = buffer;
    for (; *p; ++p)
    {
        if (*p == ' ')
              *p = '_';
    }



      printf("%s",buffer);
      fopen(buffer,"w");

      return 0;
    }

When I executed this program, the file name doesn't have '_' and instead it has empty spaces even though the program states that ' ' are replaced by '_'.

Upvotes: 0

Views: 249

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

If p is a pointer to a string, loop for (; *p; ++p) iterates over the characters of the string; note that condition *p means "as long as the value to which p currently points to is not equal 0 (i.e. the string termination character)", and that ++p moves the pointer to the next character. Expression if (*p == ' ') *p = '_' simply means "if the current character is a blank, replace it with an '_'".

If your file name still contains "blanks", it might be the case that these blanks are not ' ' but other characters that shine as a blank (like, for example, a tab '\t'). You could use if (isblank(*p)) *p = '_' instead; and you could add if (*p == '\n') { *p=0; break; } in order to eliminate new lines and truncate the filename at such an occurrence.

Upvotes: 1

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

This loop iterates through buffer to replace spaces by underscores.

Explanation:

char *p = buffer; // `p` is a pointer to the beginning of `buffer`
for (; *p ; ++p) // Increment `p` to point to the next character, until a `\0` is reached
{
    if (*p == ' ') // Check if the character at pointer `p` is a space
        *p = '_'; // If so, replace it by an underscore
}

Upvotes: 0

Related Questions