forked from Bananymous/banan-os
cat: Use write() instead of puts to print file contents
This allows printing files that contain null bytes behave more like you would expect
This commit is contained in:
parent
e780eaa45f
commit
7ce8e2d57b
|
@ -1,18 +1,18 @@
|
||||||
|
#include <fcntl.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
bool cat_file(FILE* fp)
|
bool cat_file(int fd)
|
||||||
{
|
{
|
||||||
char buffer[1025];
|
char buffer[1024];
|
||||||
size_t n_read;
|
size_t n_read;
|
||||||
while ((n_read = fread(buffer, 1, sizeof(buffer) - 1, fp)) > 0)
|
while (ssize_t n_read = read(fd, buffer, sizeof(buffer)))
|
||||||
{
|
{
|
||||||
buffer[n_read] = '\0';
|
if (n_read == -1)
|
||||||
fputs(buffer, stdout);
|
{
|
||||||
}
|
perror("read");
|
||||||
if (ferror(fp))
|
return false;
|
||||||
{
|
}
|
||||||
perror("fread");
|
write(STDOUT_FILENO, buffer, n_read);
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -25,21 +25,21 @@ int main(int argc, char** argv)
|
||||||
{
|
{
|
||||||
for (int i = 1; i < argc; i++)
|
for (int i = 1; i < argc; i++)
|
||||||
{
|
{
|
||||||
FILE* fp = fopen(argv[i], "r");
|
int fd = open(argv[i], O_RDONLY);
|
||||||
if (fp == nullptr)
|
if (fd == -1)
|
||||||
{
|
{
|
||||||
perror(argv[i]);
|
perror(argv[i]);
|
||||||
ret = 1;
|
ret = 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!cat_file(fp))
|
if (!cat_file(fd))
|
||||||
ret = 1;
|
ret = 1;
|
||||||
fclose(fp);
|
close(fd);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (!cat_file(stdin))
|
if (!cat_file(STDIN_FILENO))
|
||||||
ret = 1;
|
ret = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue