Rudimentary cat

TkTkorrovi 0 Tallied Votes 101 Views Share

Similar to cat in unix textutils. You can actually edit files with these. Remember that ctrl-z sends end-of-file in windows, and ctrl-d in linux.

/*
** rcat.c -- rudimentary cat, public domain by tkorrovi@mail.com
** ctrl-z sends end-of-file in windows, ctrl-d in linux
*/

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

/*
** Inherited versions of the file operations. These might be
** slow though for character operations, so might be better
** to use fread and fwrite instead, to operate with larger
** amounts of data at a time. Such inherited functions make
** the actual program much more clear, eliminating the need
** to check errors on every step.
*/

FILE *openfile (const char *name, const char *mode)
{
	FILE *output;

	output = fopen (name, mode);
	if (output == NULL) exit (1);
	return output;
}

int closefile (FILE *stream)
{
	int output;

	output = fclose (stream);
	if (output == EOF) exit (1);
	return output;
}

int gch (FILE *stream)
{
	int output;

	output = fgetc (stream);
	if (ferror (stream)) exit (1);
	return output;
}

int pch (char c, FILE *stream)
{
	int output;

	output = fputc (c, stream);
	if (ferror (stream)) exit (1);
	return output;
}

int main (int argc, char *argv [])
{
	FILE *file;
	int ch, i;

	if (argc == 1)
	{
		while ((ch = gch (stdin)) != EOF) pch (ch, stdout);
	}
	else
	{
		for (i = 1; i < argc; i++)
		{
			file = openfile (argv [i], "r");
			while ((ch = gch (file)) != EOF) pch (ch, stdout);
			closefile (file);
		}
	}
	return 0;
}
Dani 4,329 The Queen of DaniWeb Administrator Featured Poster Premium Member

Thanks :) And for a more complete cat, check out: http://www.daniweb.com/code/snippet216.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.