Question

File structure is a structure, which is according to a required format that operating system can...

File structure is a structure, which is according to a required format that operating system can
understand. A file has a certain defined structure according to its type. A text file is a sequence
of characters organized into lines. A source file is a sequence of procedures and functions. An
object file is a sequence of bytes organized into blocks that are understandable by the machine.
When operating system defines different file structures, it also contains the code to support
these file structure. Unix, MS-DOS support minimum number of file structure.
Tasks
Task 1:
The first task is to build a program like tail, which is a utility available on Linux systems that
prints the last N lines of a file. You specify the value for N as a command line option. Do a
man tail to find out more about this tool.
Your task is to write a C program that prints out the last few lines of a file. To invoke your
program, one should type:
mytail -n file
where n is the number of lines at the end of the file to print. You are only allowed to use pure
UNIX system calls such as open(), read(), and close().
NOTE:-
Do not use function calls like fopen(), fread(), getline(), fseek() etc.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Here is the code and output attached
// plz comment if you need any clarification
// do upvote if you like the answer

// CODE
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/fcntl.h>
#include<unistd.h>
#define bool short

// function to check if a file exists or not
bool isFileExists(const char* fileName) {
struct stat buffer;
return (stat(fileName, &buffer) == 0);
}

// function to find the number of lines in a file
int findNumLinesInFile(const char* fileName) {
  
int fd = open(fileName, O_RDONLY); // open the file in read only mode

if(fd < 0) { // if any error occurred, terminate
printf("Error: Unable to open file %s", fileName);
return -1;
}
int lines = 0;
do {
char *c = (char *) calloc(100, sizeof(char));
int b_r = read(fd, c, 10);
if(b_r <= 0) {
break; // either reached EOF or any error in read
} else {
c[b_r] = '\0';
}
  
for(int i = 0; i < b_r; i++) {
if(c[i] == '\n'){
lines++;
}
}
} while(1);
close(fd); // close the file
return lines;
}

// function to tail the contents of a file
int tail(const int n, const char* fileName) {
if(!isFileExists(fileName)) {
printf("Error: Unable to locate file named %s\n", fileName);
return -1;
}

// first find the number of lines in the file
int lines = findNumLinesInFile(fileName);
//printf("Number of lines in file : %d\n", lines);

int fd = open(fileName, O_RDONLY); // open the file in read only mode

if(fd == -1) { // if any error occurred, terminate
printf("Error: Unable to open file %s", fileName);
return -1;
}
  
// find out from which line you should start printing the
// file contents, it should be last n lines
// so remove n from number of lines, for those many lines
// you do not print contents to terminal
int line_to_start = lines - n;
while(1) {
char *c = (char *) calloc(102, sizeof(char)); // create a buffer
int b_r = read(fd, c, 100); // read into buffer
if(b_r <= 0) { // if num of bytes read is <= 0, then stop reading
break; // either reached EOF or any error in read
} else {
c[b_r] = '\0'; // else form a string with c
}
  
// now for every line,
// if line to start is <= 0
// then print complete contents read to buffer
if(line_to_start <= 0) {
printf("%s", c);
} else { // otherwise
for(int i = 0; i < b_r; i++) { // loop over contents
if(line_to_start > 0) { // if still not reached last n lines
if(c[i] == '\n') { // read a new line char in buffer
line_to_start--; // decrease the number of lines to ommit, by 1.
}
}
// if in this current buffer if we crossed the last line that we need to
// skip, then print the rest of the chars to console
if(line_to_start <= 0) {
printf("%c", c[i]);
}
}
}
}
close(fd); // close the file
return 0;
}

// Driver program
int main(int argc, char** argv) {
if(argc < 2) {
printf("USAGE: mytail <n> <filename>\n");
exit(0);
}

int n; // number of lines to print
char* fileName; // name of the file to tail
  
//printf("argv1 : %s, argv2 : %s\n", argv[1], argv[2]);
n = atoi(argv[1]); // read the n
fileName = (char*) malloc(sizeof(char) * (strlen(argv[2])+1) );
strcpy(fileName, argv[2]); // read the filename
//printf("n:%d file:%s\n", n, fileName);

return tail(n, fileName); // tail the file contents
}

// OUTPUT

Add a comment
Know the answer?
Add Answer to:
File structure is a structure, which is according to a required format that operating system can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Identify and list all the User defined Functions to be used in the system #include <stdio.h>...

    Identify and list all the User defined Functions to be used in the system #include <stdio.h> ///for input output functions like printf, scanf #include <stdlib.h> #include <conio.h> #include <windows.h> ///for windows related functions (not important) #include <string.h> ///string operations /** List of Global Variable */ COORD coord = {0,0}; /// top-left corner of window /** function : gotoxy @param input: x and y coordinates @param output: moves the cursor in specified position of console */ void gotoxy(int x,int y) {...

  • need this in c programming and you can edit the code below. also give me screenshot...

    need this in c programming and you can edit the code below. also give me screenshot of the output #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LINE_SIZE 1024 void my_error(char *s) { fprintf(stderr, "Error: %s\n", s); perror("errno"); exit(-1); } // This funciton prints lines (in a file) that contain string s. // assume all lines has at most (LINE_SIZE - 2) ASCII characters. // // Functions that may be called in this function: // fopen(), fclose(), fgets(), fputs(),...

  • The purpose of this assignment is to develop solutions that perform File IO and objects. Problem specifications are shown below with my changes in blue. 1. File Previewer Write a program that asks...

    The purpose of this assignment is to develop solutions that perform File IO and objects. Problem specifications are shown below with my changes in blue. 1. File Previewer Write a program that asks the user for the name of a text file. The program should display the first 10 lines of the file on the screen. If the file has fewer than 10 lines, the entire file should be displayed along with a message indicating the entire file has been...

  • C++ requirements The store number must be of type unsigned int. The sales value must be...

    C++ requirements The store number must be of type unsigned int. The sales value must be of of type long long int. Your program must properly check for end of file. See the section Reading in files below and also see your Gaddis text book for details on reading in file and checking for end of file. Your program must properly open and close all files. Failure to follow the C++ requirements could reduce the points received from passing the...

  • In this assignment you’ll implement a data structure called a trie, which is used to answer...

    In this assignment you’ll implement a data structure called a trie, which is used to answer queries regarding the characteristics of a text file (e.g., frequency of a given word). This write-up introduces the concept of a trie, specifies the API you’re expected to implement, and outlines submission instructions as well as the grading rubric. Please carefully read the entire write-up before you begin coding your submission. Tries A trie is an example of a tree data structure that compactly...

  • Need this in c programming

    Question:Many files on our computers, such as executables and many music and video files, are binary files (in contrast to text files). The bytes in these files must be interpreted in ways that depend on the file format. In this exercise, we write a program data-extract to extract integers from a file and save them to an output file. The format of the binary files in this exercise is very simple. The file stores n integers (of type int). Each...

  • Hello Guys. I need help with this its in java In this project you will implement...

    Hello Guys. I need help with this its in java In this project you will implement a Java program that will print several shapes and patterns according to uses input. This program will allow the use to select the type (say, rectangle, triangle, or diamond), the size and the fill character for a shape. All operations will be performed based on the user input which will respond to a dynamic menu that will be presented. Specifically, the menu will guide...

  • This interactive program focuses on if/else statements, Scanner, and returning values. Turn in a file named...

    This interactive program focuses on if/else statements, Scanner, and returning values. Turn in a file named Budgeter.java. To use a Scanner for console input, you must import java.util.*; in your code. This program prompts a person for income and expense amounts, then calculates their net monthly income. Below are two example logs of execution from the program. This program’s behavior is dependent on the user input (user input is bold and underlined below to make it stand out and differentiate...

  • In this exercise you will work with LU factorization of an matrix A. Theory: Any matrix A can be ...

    In this exercise you will work with LU factorization of an matrix A. Theory: Any matrix A can be reduced to an echelon form by using only row replacement and row interchanging operations. Row interchanging is almost always necessary for a computer realization because it reduces the round off errors in calculations - this strategy in computer calculation is called partial pivoting, which refers to selecting for a pivot the largest by absolute value entry in a column. The MATLAB...

  • CSC 142 Music Player You will complete this project by implementing one class. Afterwards, your program...

    CSC 142 Music Player You will complete this project by implementing one class. Afterwards, your program will play music from a text file. Objectives Working with lists Background This project addresses playing music. A song consists of notes, each of which has a length (duration) and pitch. The pitch of a note is described with a letter ranging from A to G.   7 notes is not enough to play very interesting music, so there are multiple octaves; after we reach...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT