CSC 272 - Software II: Principles of Programming Languages

Dr. R. M. Siegfried

A Program in C to Write integers in a text file

#include	<stdio.h>/* To include the standard I/O library */
#include	<stdlib.h>	/* To include the standard library
					Turbo C requires it for exit() */

#define		ARRAYLEN	20	/* Replace ARRAYLEN with 20 */
#define		FILENAMELEN	30	/* Replace FILENAMELEN with 30 */


/* Prototypes for the functions used */
int	readarray(int x[]);	/* ReadArray returns an integer  - # of
					numbers in array - &  it has one
					parameter - an array of
						integers */
void	writefile(FILE *outfile, int x[], int n);	/* WriteArray
						returns no value */

/*
 * main() -	Read an array of integers and write it in a text file 
 */
int	main(void)
{
	FILE	*outfile;	/* Pointer to output file */
	char	filename[FILENAMELEN];	
	int	n, i, x[ARRAYLEN];

	printf("Enter file name ->\t");
	gets(filename);

        /* Standard idiom for opening an output file */  
	if ((outfile = fopen(filename, "w")) == NULL)	{
		printf("Cannot open %s\n", filename);
		exit(1);
	}

	n = readarray(x); /* Function call */
	/* Write the array */
	for (i = 0;  i < n;  i++)
		printf("%d\n", x[i]); /* Print the number in decimal
						format -   \n is
						newline */

	/* Call the function that writes the file */
	writefile(outfile, x, n);
	fclose(outfile);
	return(0);
}

/*
 * Readarray() - 	Read the array
 *			Arrays are passed by reference
 */
int	readarray(int x[])
{
	int	n = 0;

	/* Read each value */
	do	{
		printf("Enter a value\t?");
		scanf("%d", &x[n++]);	/* Read an integer */
	} while (x[n-1] != 0 && n < ARRAYLEN);

	/* Array indices run from 0 to n-1 */  
	n = (n == ARRAYLEN)? n - 2: n - 1;

	return(n);
}

void	writefile(FILE *outfile, int x[], int n)
{
	int	i;

	for (i = 0;  i < n;  i++)
		fprintf(outfile, "x[%d] = %d\n", i, x[i]);

}

[Back to the C Program Index]