Solved

How to reverse strings effeciently

Posted on 2003-10-22
7
251 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
Comment Utility
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
Comment Utility
Are there any string reversing functions in the standard C libraries? I cant seem to find strrev().
0
 
LVL 1

Expert Comment

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

Nope
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 6

Expert Comment

by:Ajar
Comment Utility
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
Comment Utility
strrev is not included in ANSI standard and is available on some platforms
0
 

Author Comment

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

Expert Comment

by:Kdo
Comment Utility

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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

762 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

9 Experts available now in Live!

Get 1:1 Help Now