Solved

How to reverse strings effeciently

Posted on 2003-10-22
7
261 Views
Last Modified: 2012-05-04
I have a program that reverses the contents of a file byte by byte, but that is rather inefficient and I would like to take larger chunks of bytes and reverse those; still keeping the order (reversed) but doing it faster and with less iterations.  Here is the byte by byte code. The file to read is given as the first comand line argument.

#include <fcntl.h>
const char lf = '\n';

int main(int argc, char* argv[]) {
  int  inputFD;
  char inputByte;
  long currentLoc;

  inputFD = open(*++argv, O_RDONLY);
  currentLoc = lseek(inputFD, -1L, 2);
  while (currentLoc >= 0) {
    read(inputFD, &inputByte, 1);
    write(1, &inputByte, 1);
    currentLoc = lseek(inputFD, -2L, 1);
  }
  write(1, &lf, 1);
  close(inputFD);
}

Thanks for any suggestions.

-Shiromagius
0
Comment
Question by:Shiromagius
7 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 125 total points
ID: 9596993
1. read in a chunk
2. reverse it in a buffer (use strrev() or any other function that suits your data )
3. write it

e.g. lseek to 500 bytes from end
read 500 bytes into buffer
print the buffer in reverse
next lseek to 500*number of iterations

return value of lseek can be used for terminating the loop
0
 

Author Comment

by:Shiromagius
ID: 9597106
Are there any string reversing functions in the standard C libraries? I cant seem to find strrev().
0
 
LVL 1

Expert Comment

by:chikucoder
ID: 9597169
>>Are there any string reversing functions in the standard C libraries? I cant seem to find strrev().

Nope
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 6

Expert Comment

by:Ajar
ID: 9597265
I suggest  following
read the whole file  in a single go and then   reverse the whole string

SAMPLE program ..

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char * argv[])
{
FILE * f ;
char * c ;
long   len;
struct stat sb;
if(argc < 2) return 0;
//FIND FILE STATASTICS ...
if(stat(argv[1],&sb) {printf("FILE NOT EXISTANT %s \n",&argv[1]);return 0;}
// ALLOCATE MEMORY EQUAL TO FILE SIZE
c = (char* ) malloc(sb.st_size);
//READ FILE
f = fopen(argv[1],"r");
len = fread(c,1,sb.st_size,f);
fclose(f);
//Print the reverse of string
{
long k = len
while(k) putchar ( c[k--]);
}
// REverse the string in memory
{
  long k = len/2;
  while(k) {c[k]^=c[len-k]^=c[k]^=c[len-k];k--}
}
//DO PROCESSING WITH c

free(c);
return 0;
}
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9597441
strrev is not included in ANSI standard and is available on some platforms
0
 

Author Comment

by:Shiromagius
ID: 9597816
Thanks everyone. I got it all worked out. Thank you everyone for their comments.
0
 
LVL 45

Expert Comment

by:Kdo
ID: 9605964

I know that this has been closed, but you CAN reverse the entire file easily and reasonably efficiently.  Use the mmap() function to map the entire file to paged memory and then just print the array backwards.  Here's a shell of a program to do that:

#include <stdlib.h>
#include <sys/mman.h>
#include <sys/type.h>
#include <sys/stat.h>
#include <unistd.h>

int     FileHandle;
char *FileName = "TestFile";  // Hard coded for simplicity
char *FileBuffer;

FILE *Output;
char *OutputName = "NewFile";

struct stat  Stat;

main ()
{
    int idx;

/*  open input file  */

    FileHandle = open (FileName, O_RDONLY);  // Test for errors
    fstat (FileHandle, &Stat);
    FileBuffer = mmap (NULL, Stat.st_size, PROT_READ, MAP_SHARED, FileHandle, 0);

/*  open output file  */

   Output = fopen (OutputName, "w");

/*  copy file  */

    for (idx = Stat.st_size; idx; idx--)
      putc (FileBuffer+idx, Output);

    fclose (Output);
    munmap (FileBuffer, Stat.st_size);
    close (FileHandle);
}



Kent
0

Featured Post

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now