Question

Writing Unix Utilities in C (not C++ or C#) my-cat The program my-cat is a simple...

Writing Unix Utilities in C (not C++ or C#)

my-cat

The program my-cat is a simple program. Generally, it reads a file as specified by the user and prints its contents. A typical usage is as follows, in which the user wants to see the contents of my-cat.c, and thus types:

prompt> ./my-cat my-cat.c
#include <stdio.h>
...

As shown, my-cat reads the file my-cat.c and prints out its contents. The "./" before the my-cat above is a UNIX thing; it just tells the system which directory to find my-cat in (in this case, in the "." (dot) directory, which means the current working directory).

To create the my-cat binary, you'll be creating a single source file, my-cat.c, and writing a little C code to implement this simplified version of cat. To compile this program, you will do the following:

$ gcc -o my-cat my-cat.c -Wall -Werror
$ 

This will make a single executable binary called my-cat which you can then run as above.

You'll need to learn how to use a few library routines from the C standard library to implement the source code for this program, which we'll assume is in a file called my-cat.c. All C code is automatically linked with the C library, which is full of useful functions you can call to implement your program. Learn more about the C library at https://en.wikipedia.org/wiki/C_standard_library

For this project, we recommend using the following routines to do file input and output: fopen(), fgets(), and fclose(). Whenever you use a new function like this, the first thing you should do is read about it.

On UNIX systems, the best way to read about such functions is to use what are called the man pages (short for manual). To access the man page for fopen(), for example, just type the following at your UNIX shell prompt:

$ man fopen

We will also give a simple overview here. The fopen() function "opens" a file, which is a common way in UNIX systems to begin the process of file access. In this case, opening a file just gives you back a pointer to a structure of type FILE, which can then be passed to other routines to read, write, etc.

Here is a typical usage of fopen():

FILE *fp = fopen("my-cat.c", "r");
if (fp == NULL) {
    printf("cannot open file\n");
    exit(1);
}

A couple of points here. First, note that fopen() takes two arguments: the name of the file and the mode. The latter just indicates what we plan to do with the file. In this case, because we wish to read the file, we pass "r" as the second argument. Read the man pages to see what other options are available.

Second, note the critical checking of whether the fopen() actually succeeded. This is not Java where an exception will be thrown when things goes wrong; rather, it is C, and it is expected (in good programs, i.e., the only kind you'd want to write) that you always will check if the call succeeded. Reading the man page tells you the details of what is returned when an error is encountered; in this case, the macOS man page says:

Upon successful completion fopen(), fdopen(), freopen() and fmemopen() return
a FILE pointer.  Otherwise, NULL is returned and the global variable errno is
set to indicate the error. 

Thus, as the code above does, please check that fopen() does not return NULL before trying to use the FILE pointer it returns.

Third, note that when the error case occurs, the program prints a message and then exits with error status of 1. In UNIX systems, it is traditional to return 0 upon success, and non-zero upon failure. Here, we will use 1 to indicate failure.

Side note: if fopen() does fail, there are many reasons possible as to why. You can use the functions perror() or strerror() to print out more about why the error occurred; learn about those on your own (using ... you guessed it ... the man pages!).

Once a file is open, there are many different ways to read from it. The one we're suggesting here to you is fgets(), which is used to get input from files, one line at a time.

To print out file contents, just use printf(). For example, after reading in a line with fgets() into a variable buffer, you can just print out the buffer as follows:

printf("%s", buffer);

Note that you should not add a newline (\n) character to the printf(), because that would be changing the output of the file to have extra newlines. Just print the exact contents of the read-in buffer (which, of course, many include a newline).

Finally, when you are done reading and printing, use fclose() to close the file (thus indicating you no longer need to read from it).

Details

  • Your program my-cat can be invoked with one or more files on the command line; it should just print out each file in turn.
  • In all non-error cases, my-cat should exit with status code 0, usually by returning a 0 from main() (or by calling exit(0)).
  • If no files are specified on the command line, my-cat should just exit and return 0. Note that this is slightly different than the behavior of normal UNIX cat (if you'd like to, figure out the difference).
  • If the program tries to fopen() a file and fails, it should print the exact message "my-cat: cannot open file" (followed by a newline) and exit with status code 1. If multiple files are specified on the command line, the files should be printed out in order until the end of the file list is reached or an error opening a file is reached (at which point the error message is printed and my-cat exits)
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Source Code in C:

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fp; //creating file pointer
fp = fopen("File2.c","r"); //opening file in read mode, I have worked here with File2.c, you can change it
char buffer[100]; //creating string to store each line
if (fp == NULL)
{
perror("Error while opening the file. ");
exit(EXIT_FAILURE);
}
while(fgets(buffer,100,fp)) //while file has not been read fully
{
printf("%s ",buffer);
}
}

Output:

Add a comment
Know the answer?
Add Answer to:
Writing Unix Utilities in C (not C++ or C#) my-cat The program my-cat is a simple...
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
  • Write a C Program that uses file handling operations of C language to copy the contents...

    Write a C Program that uses file handling operations of C language to copy the contents of a file called “original.dat” to another file called “copy2.dat”. Here, you will read and write from/to the files line by line with the help of fgets() and fputs() functions. Sample file “original.dat” has been provided. Please note that the new file “copy2.dat” should have exactly same contents as in “original.dat”. #include <stdio.h> int main() { FILE *fptr1, *fptr2; if((fptr1=fopen("original.dat","r"))==NULL) printf("\n Error opening File");...

  • Below is a basic implementation of the Linux command "cat". This command is used to print...

    Below is a basic implementation of the Linux command "cat". This command is used to print the contents of a file on the console/terminal window. #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) {FILE *fp; if(2 != argc) {priritf ("Usage: cat <filename>\n"); exit(1);} if ((fp = fopen(argv[1], "r")) == NULL) {fprintf (stderr, "Can't. open input file %s\n", argv[1]); exit (1);} char buffer[256]; while (fgets(X, 256, fp) != NULL) fprintf(Y, "%s", buffer); fclose(Z); return 0;} Which one of the following...

  • UNIX is all about manipulating files and input/output streams fluidly, so it is important to get a strong grasp of how...

    UNIX is all about manipulating files and input/output streams fluidly, so it is important to get a strong grasp of how this fundamentally works at the system call level to understand higher-level system programming concepts. Every program automatically has three file descriptors opened by the shell standard input standard output standard error 1 2 One can use read and write other open file. Normally, standard input and output on the terminal are line-buffered, so, for example, the specified number of...

  • Overview Writing in the C language, implement a very basic shell, called smash. In this project,...

    Overview Writing in the C language, implement a very basic shell, called smash. In this project, we will work on processing strings and using the appropriate system calls. Build System setup Before we can start writing code we need to get our build system all setup. This will involve writing a very simple makefile. You should leverage your Makefile project for this part of the assignment! Write a Makefile that provides the three targets listed below all - The default...

  • QUESTION 1 What will be the output of following Unix command: find / -name ‘*’ A....

    QUESTION 1 What will be the output of following Unix command: find / -name ‘*’ A. List all files and directories recursively starting from / B. List a file names * in / C. List all files in / directory D. List all files and directories in / directory QUESTION 2 Which command is used to extract a column/field from a text file / input. A. paste B. get C. cut D. tar QUESTION 3 Which command creates an empty...

  • The program is written in c. How to implement the following code without using printf basically...

    The program is written in c. How to implement the following code without using printf basically without stdio library? You are NOT allowed to use any functions available in <stdio.h> . This means you cannot use printf() to produce output. (For example: to print output in the terminal, you will need to write to standard output directly, using appropriate file system calls.) 1. Opens a file named logfle.txt in the current working directory. 2. Outputs (to standard output usually the...

  • C ++ Implement cat command The purpose of this assignment is to provide practice using the...

    C ++ Implement cat command The purpose of this assignment is to provide practice using the system calls we discussed for working with files on a UNIX system. You will be writing a basic implementation of the cat command using C++. Description As you should recall, the cat command takes a list of files as command line arguments. It then opens each file in turn, writing each file’s entire contents to standard output in the order they were supplied. You...

  • Reading and Writing Complete Files in C: The first part of the lab is to write...

    Reading and Writing Complete Files in C: The first part of the lab is to write a program to read the complete contents of a file to a string. This code will be used in subsequent coding problems. You will need 3 functions: main(), read_file() and write_file(). The main function contains the driver code. The read_file() function reads the complete contents of a file to a string. The write_file() writes the complete contents of a string to a file. The...

  • Please, please help with C program. This is a longer program, so take your time. But...

    Please, please help with C program. This is a longer program, so take your time. But please make sure it meets all the requirements and runs. Here is the assignment: I appreciate any help given. Cannot use goto or system(3) function unless directed to. In this exercise you are to create a database of dogs in a file, using open, close(), read, write(), and Iseek(). Do NOT use the standard library fopen() ... calls! Be sure to follow the directions!...

  • My question is listed the below please any help this assignment ; There is a skeleton...

    My question is listed the below please any help this assignment ; There is a skeleton code:  copy_file_01.c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char ch ; FILE *source , *target;    if(argc != 3){ printf ("Usage: copy file1 file2"); exit(EXIT_FAILURE); } source = fopen(argv[1], "r"); if (source == NULL) { printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } target = fopen(argv[2], "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch...

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