I recently wrote a program to determine my current working directory using getcwd(). getcwd() returns the starting address of the character array supplied by the programmer. I have written a very simple program and as I am not an experienced C program can anyone mention what I can do to make this program more efficient? I have defined an array which contains a random number of characters and I pass the base address of this to the function getcwd(). I recieve the base address of the modified array and proceed to print it by incrementing the char pointer which will then point to the next char. My problem is that I want to print only that string which is meaningful and not the garbage values. How do I do that??

#include<stdio.h>
#include <unistd.h>
int main(){

char buffer[250];
char *buf=getcwd(buffer,250);
if(buf==NULL)
printf("Error!!");
else
{
int i;
for(i=0;i<250;i++)
{
printf("%c",*buf);
buf++;
}
}
return 0;
}

can anyone mention what I can do to make this program more efficient?

This is a case where I'd say you have no reason to worry about efficiency.

My problem is that I want to print only that string which is meaningful and not the garbage values. How do I do that??

getcwd() returns a string. All you need to do is print a string as normal:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    char buf[BUFSIZ];

    if (!getcwd(buf, sizeof buf)) {
        perror("Error getting current working directory");
    }
    else {
        puts(buf);
    }

    return 0;
}

Also, in my code if you replace %c by %s in the last printf statement the compiler doesn't detect any error but the program crashes! Why is this happening?

Is there any site out there which can provide documentation of all the functions of all standard libraries??

Also, in my code if you replace %c by %s in the last printf statement the compiler doesn't detect any error but the program crashes! Why is this happening?

If you change %c to %s, you must also change *buf to just buf. But neither of those changes make the loop any less wrong. Remove it entirely:

else
{
    printf("%s", buf);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.