Could you explain why? I thought that would be very memory efficient. I use an array of only size 1 and replace that character each time. I am not a pro so I might be missing something here.
Printable View
Could you explain why? I thought that would be very memory efficient. I use an array of only size 1 and replace that character each time. I am not a pro so I might be missing something here.
Yes, I don't deny you that it's memory efficient. But since your stack [which is where your local variables are stored] will certainly be at the very least 4KB, I don't think putting 1000 bytes on it would be too much of a "waste".
The ineffecicency I'm referring to is the fact that a single byte read from read() is going to take many hundreds of CPU cycles, whilst a read() of 1000 bytes will probably only add a few hundred to a few thousand cycles [compared to a few hundred thousand cycles to read 1000 bytes as a loop of read() calls]. Each time you make calls into the OS, you spend a large amount of time just transitioning from your application into the OS and back again. If you can amortize that over a reasonable amount of bytes read from a file (or such), then you get a much lower overhead per byte read.
--
Mats
Ah I see now. I redid the program using 1024 bytes and without lseek.
It works right now marvelously. Thank you mats for all your help!Code:#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int i;
int x;
int fd;
char buffer[1024];
i = 1;
if (argc <= 1)
{
my_putstr("Usage: Please enter 1 or more parameters");
my_putstr("\n");
}
while (i < argc)
{
x = 1;
fd = open(argv[i], O_RDONLY);
if (!fd)
{
my_putstr("Error reading file");
my_putstr("\n");
}
else
{
while (x > 0)
{
x = read(fd, buffer, 1024);
buffer[x] = '\0';
my_putstr(buffer);
}
}
close(fd);
i++;
}
return (0);
}
Actually, you are now setting buffer[1024] = 0 if your file is bigger than 1024 bytes - that is a buffer overflow. Your buffer needs to be (at least) 1025 long.
[Of course, it still cut the file short if there's a zero-byte in there, but I guess most people don't "cat" files other than text - although I've certainly been known to do that - and I mean on purpose, rather than an accidental binary file].
Edit: You also probably should say "Error opening file" rather than "reading".
Edit2: Some further "tidiness" comments:
1) I would use a "for(i = 1; i < argc; i++)" as the loop over arguments.
2) If you use "do ... while(x > 0);" instead of while, you don't need to initialize x to 1.
3) You should check if fd > 0, not if fd != 0 - zero is a valid file-descriptor [technically, fd is an index into a array, and of course, in C, arrays are zero-based, so the first file opened will have fd = 0].
--
Mats