Modifying contents in the middle of a file
Usage of lseek() system call.
-
Create a test input file
echo 0123456789 > numbers.txt
-
You can start with the following program:
#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char const *argv[]) { int fd = open("numbers.txt", O_RDONLY); long l; l = lseek(fd, 0L, SEEK_END); printf("Length of the file is %ld bytes.\n", l); close(fd); return 0; }
- Look at the documentation page of the lseek() system call and attempt to explain the example program above.
-
Change the program to modify the input file into
012abcd789
(use lseek() function and open the output file only for writing) -
Reset the file into its original contents
0123456789
-
Change the program to modify the input file into
012abcd789
and then to012abcd7xyz
(use lseek() function and open the output file only for writing) -
Reset the file into its original contents
0123456789
-
Change the program to modify the input file into:
0123456789 \0\0\0 ... \0\0\0 xyz
, where the\0
represent byte with value zero. Make sure that the sequence of\0
characters is at least 10000 bytes.- Accomplish this task by usage of the write system call. Save output in a file named output1 .
- Accomplish this task by usage of lseek system call. Save output in a file named output1 .
- Observe number of blocks in the output files (use program stat)
Listing directory contents
- Examine example at a manpage of the stat() system call
-
Examine the following program:
/* * C Program to List Files in Directory */ #include <dirent.h> #include <stdio.h> int main(void) { DIR *d; struct dirent *dir; d = opendir("."); if (d) { while ((dir = readdir(d)) != NULL) { printf("%s\n", dir->d_name); } closedir(d); } return(0); }
Homework 2
/*
* C Program to List Files in Directory
*/
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
- Modify the program above to use first command argument line parameter as a directory name similarly as the ls command does.
-
Merge the file stat and directory listing programs into one which would emulate functionality of the
ls -l
command.
/*
* C Program to List Files in Directory
*/
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}