|
The contents of this page are licensed under the following license
Operating System
Copy files |
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char buf[1024];
int fd_one, fd_two;
int count;
if (argc < 3)
{
printf("usage: %s <src_file> <dest_file>\n", argv[0]);
exit(1);
}
/* open source file */
fd_one = open(argv[1], O_RDONLY);
if (fd_one == -1)
{
perror("Error file open src_file");
exit(1);
}
/* open destination file */
fd_two = open(argv[2], O_WRONLY | O_CREAT, 0644);
if (fd_two == -1)
{
perror("Error file open dest_file");
exit(1);
}
/* copy source file data */
do
{
count = read(fd_one, buf, 1024);
if (count > 0) write(fd_two, buf, count);
} while(count > 0);
/* close files */
close(fd_one);
close(fd_two);
return 0;
}
|
|
File size |
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int fd;
int size;
if (argc < 2)
{
printf("usage: %s <file_name>\n", argv[0]);
exit(1);
}
/* open file */
fd = open(argv[1], O_RDONLY);
if (fd == -1)
{
perror("Error open file");
exit(1);
}
/* check file size */
size = lseek(fd, 0, SEEK_END);
printf("%s = %dB\n", argv[0], size);
/* close file */
close(fd);
}
|
|
Characters, words and lines counter |
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 1024
int main(int argc, char* argv[])
{
int fd;
int size;
char buf[BUF_SIZE];
short space=0;
int chars=0, words=0, lines=0, foo;
if (argc < 2)
{
printf("usage: %s <file_name>\n", argv[0]);
exit(1);
}
/* open file */
fd = open(argv[1], O_RDONLY);
if (fd == -1)
{
perror("Error open file");
exit(1);
}
/* count lines, words and characters */
while((size=read(fd, buf, BUF_SIZE))>0)
{
for (foo=0; foo<size; foo++)
{
if (buf[foo] == '\n') lines++;
if (isascii(buf[foo]))
{
chars++;
if (chars == 1) words = 1;
if (space && !isspace(buf[foo])) { words++; space=0; }
}
if (isspace(buf[foo])) space=1;
}
}
printf("%s: %d\t%d\t%d\n", argv[1], lines, words, chars);
/* close file */
close(fd);
}
|
October, 16th 2006
© Michał Kalewski