UbuntuThis forum is for the discussion of Ubuntu Linux.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
printf("%s\n",buff) will output the contents buff up to but not including a NULL character. Any printable character that is in buff between the 5th element and a NULL character will be displayed.
You can add a NULL (0) character to buff or only print 5 characters. Here are a few examples.
Code:
buff[5]=0;
printf("%s\n", buff); // will print to the first NULL character
printf("%.5s\n",buff); // Will print first 5 characters
length=5;
printf("%.*s\n", length, buff); // will print number of characters defined by length
Yes, Just cleaning your buffer won't solve the problem.
Can you explain whats going on here:
in plain english?
Oh! Spelling mistake is here. I wanted to use read() function as that place of fread(). read(f,buff,5); statement reads first 5 characters from the file opened by f descriptor.
The %s format takes a nul terminated string you need to do the following
Code:
char buf[10];
f=open("file.txt",O_RDONLY);
ok=fead(f,buf,5);
if (ok<0) buf[0]='\0';
else buf[ok]='\0';
printf("%s\n",buf);
Note you have to nul terminate all strings explicitly. And have to allow space for it, that is buf[10] gives 10 character positions one of which has to be the nul byte leaving ipto 9 for data
Last edited by rhubarbdog; 12-01-2017 at 10:30 PM.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.