Canul Podkopayeva wrote:

> Code compiles and everything but doesn't operate like its supposed to. 
> It some how after printing loler adds two or 4 additional chars

First, your file contained CRLF-terminated lines, which is incorrect
for a Unix system. However, gcc will cope with it.

> #include <stdio.h>
> #include <sys/stat.h>
> #include <fcntl.h>
> #include <unistd.h>
> 
> #define BUFFER 256
> 
> void main(int argc, char *argv[])
> {
>     int fd;
>     char loler[BUFFER];
> 
>     if(argc < 2)
>     {
>         printf("˛˛˛Canul˛˛˛\n");

You shouldn't use top-bit-set characters in C source code. You should
use octal escapes (i.e. \262) instead.

>         fprintf(stderr, "Usage:<%s> <name of file to cat>\n", argv[0]);
>         exit(0);

You should pass a non-zero value to exit() if you're terminating
because of an error.

>     }
> 
>     if((fd = open(argv[1], O_RDONLY)) < 0)
>     {
>         fprintf(stderr, "Couldn't open %s!\n", argv[1]);

You should use perror() for this; it will display the string
corresponding to the value of errno, indicating exactly why the call
failed.

>         exit(0);
>     }
>     read(fd, loler, BUFFER - 1);
>     printf("%s", &loler);
> }

1. `&loler' is incorrect; loler is itself a pointer; you should just
use `loler' instead. Again, gcc will cope with this.

2. The contents of loler[] won't generally be NUL-terminated. This is
what is causing your problem.

3. You should only use printf() if you actually need its formatting
capabilities. In this case, it would be better to use write(), i.e.

        ssize_t n;

        ...

        n = read(fd, loler, BUFFER - 1);
        if (n < 0)
        {
                perror("read");
                exit(1);
        }
        if (write(STDOUT_FILENO, loler, n) < 0)
        {
                perror("write");
                exit(1);
        }

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to