As the title states, I've been tasked to read a line from a file, reverse the first half then stick it on the end:
If that sounded a bit confusing, sample I/O:
abcdef -> defcba
It should be able to handle odd-numbered lines also:
abcdefg -> defgcba
As well as numbers, but since chars are ints it shouldn't be a problem.
Here's where the problem lies. In running the program I get this as output for the first sample input I provided:
?_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_??_???_? ???_?`?_?
Abort trap
Yeah, that's an abort trap at the end...
here's my current code:
/*
* Lab6a.c
*
*
* Created by Okysho Kenyaku on 11-11-06.
* Copyright 2011 Idome Inc. All rights reserved.
*
*/
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main(int argc, char *argv[]){
FILE*fptr;
char line [BUFSIZ];
char end[50];
char rev[50];
int i, j, k, count;
int command =0;
if (argc != 2)
{
printf("Requires valid file name.\n");
return(-1);
}
else{
fptr = fopen ( argv[1],"r" ) ;
if( fptr == NULL )
{
printf ( "Cannot find file \n" ) ;
return(-1);
}
else
{
while ( fgets ( line, sizeof line, fptr ) != NULL )
{
if ((BUFSIZ % 2) ==0)
{
j =0;
for (i = (sizeof line / 2); i < sizeof (BUFSIZ /2); i++)
{
end[j] = line[i];
j++;
}
count = j;
//reverse array
for ( i = 0 ; i < j ; i++ )
{
rev[count] = line[i];
count--;
}
//append first half on line onto end
for (i = j; i < BUFSIZ; i++) {
end[i] = rev[k];
k++;
}
for (i =0; i< BUFSIZ; i++)
{
printf("%c", end[i]);
}
printf("\n");
}
else
{
j =0;
for (i = (sizeof line / 2); i < sizeof ((BUFSIZ /2) +1); i++)
{
end[j] = line[i];
j++;
}
count = j;
//reverse array
for ( i = 0 ; i < (j -1) ; i++ )
{
rev[count] = line[i];
count--;
}
//append first half on line onto end
for (i = j; i < BUFSIZ; i++) {
end[i] = rev[k];
k++;
}
for (i =0; i< BUFSIZ; i++)
{
printf("%c", end[i]);
}
printf("\n");
}
}
}
}
}
The output is actually supposed to print to a file, but for debugging purposes I'm printing to the console.
Thanks in advance
~Oky

New Topic/Question
Reply



MultiQuote



|