Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

How to reverse strings effeciently

Posted on 2003-10-22
7
276 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
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
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:Kent Olsen
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

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

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

Suggested Solutions

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…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

856 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