In: Computer Science
****NOTE YOU MUST USE SYSTEM CALL I/O, meaning STANDARD I/O IS NOT ALLOWED THIS MEANS THAT YOU CANT USE fopen, fclose , etc
*******You are ONLY ALLOWED TO USE SYSTEM CALL I/O such as read, write, open and close (System I/O functions)
Write a C program using system call I/O to determine how many lines there are in a text file.
Here, we are using system calls I/O to determine the total number of lines in a text file.
Steps to be followed:
Please refer to the comments of the program for more clarity.
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
int main()
{
int fd,i; // Initialized the variables which we will be using throughout the program
fd = open("calls.txt", O_RDWR); // Opening the file
int lineCount = 0; // Initialized the lineCount or the lineCounter to 0
char msg[1000]; // Initialized the char array to store the contents of the text file
/*
When fd == -1, it means file is invalid and in our cases the value of fd will be 3 since the value 1 and 2 is already reserved..
*/
if(fd != -1)
{
read(fd, msg, sizeof(msg)); // Reading the file
for(i=0;i<sizeof(msg);i++)
{
if(msg[i]=='\n') // Checking the new line in the file.
lineCount++; // Increasing the counter if we find any new line
}
printf("Total number of lines: %d",lineCount); // Finally, printing the lineCount.
}
return ;
}
Sample Input-Output/Code-run:
Random file:
Output:
Note:
Please choose the file which you will be reading in the program carefully. I mean please make sure that the text file is not having any unwanted new lines, line spaces.
Please let me know in the comments in case of any confusion. Also, please upvote if you like.