My assignment is to:
Write a C program named rev to open a text file and display its contents line by
line so that the text of each line is reversed.
Here's the code I have currently (it's gonna look rough, please remember that I'm still learning):
Code:
/* Libraries */
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
int getLine ( char *src, FILE *fswitch );
int main ( int argc, char * argv[ ] )
{
char instring [ 120 ]; // holds string input from files
char numberLines [ 10 ]; // used to number lines (option)
char fileName [ 50 ]; // used to hold the name of the file
FILE * inptr; // FILE ptr as defined in stdio.h
int i, j; // counters for loops
int lineNum = 1; // lineNum counts the number of lines
int end = 0; // end quits the loop when file is scanned
if( argc == 1 ) {
printf( "Please enter a filename. Syntax: ./rev \"filename\" \"number of lines\"\n" );
return 0;
}
else if( argc == 2 )
{
strcpy( fileName, argv[1] );
}
else if ( argc == 3 )
{
strcpy( numberLines, argv[ 1 ] );
strcpy( fileName, argv[ 2 ] );
if ( strcmp( numberLines, "-n" ) != 0 ) {
return 0;
}
}
else
{
printf( "Too many arguments. Syntax: ./rev \"filename\" \"number of lines\"\n" );
return 0;
}
if ( ( inptr = fopen( fileName, "r" ) ) == NULL ) {
printf( "File could not be opened.\n" );
return 0;
}
while( end != 1 ) {
end = getLine ( instring, inptr );
if ( feof( inptr ) != 0 ) {
end = 1;
}
if( strcmp( numberLines, "-n" ) == 0 ) {
printf("%d ", lineNum );
}
for( j = 0; instring[ j ] != '\0'; j++ ) {
--j;
}
if( instring[j] == '\n' ) {
--j;
}
while( j >= 0 ) {
printf( "%c", inptr[j] );
--j;
}
lineNum = lineNum + 1;
printf( "\n" );
for( i = 0; i < 119; ) {
instring[i++] = '\0';
}
fclose( inptr );
return 0;
}
int getLine ( char *src, FILE *fswitch )
{
if( fgets( src, 81, fswitch ) != NULL ) {
if ( src[0] == '\n' )
return ( getLine( src, fswitch ) );
else
return 0;
}
else
return 1;
} // getLine
I've tried to get rid of my Syntax error at end of input error several different ways but it doesn't go away. I don't know what's causing it.