Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out a char[]

Tags:

c

I cannot for the life of me remember how to do this. This program opens a file then reads the file. All I would like it to do is print out the contents it has just read.

int main(int argc, char *argv[])
{
   char memory[1000]; //declare memory buffer size
   int fd = 0;
   int count = 1000;


   if ((fd = open(argv[1], O_RDONLY)) == -1)
   {
      fprintf(stderr, "Cannot open.\n");
      exit(1);
   }

   read(fd, memory, count);

   //printf the buffered memory contents

   return 0;
}
like image 401
Hopeless Programmer Avatar asked Dec 12 '25 01:12

Hopeless Programmer


2 Answers

printf accepts %s format to print a C-string. However, by default it requires that string to have a null-terminator (0x0 ASCII code). If you are sure it was read by the call to read then you can do this:

printf("%s\n", memory);

However, you cannot be sure. Because you don't even check how many bytes were read... or for error code. So you have to fix your code first.

Once you are done checking for errors and know how many bytes were read, you can do this:

printf("%.*s\n", (int)bytes_that_were_read, memory);

Good luck!

for (unsigned int i = 0; i < count; i++) {
  printf("%c", memory[i]);
}
like image 38
perreal Avatar answered Dec 14 '25 20:12

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!