Hello,
I have a question.
I try to print a ascii file in reverse order( bottom-top). Here is the logic.
1. Go to the botton of the file fseek(). move one character back to avoid the EOF.
2. From here read a character, print it, move the file pointer (FILE*) to 2 steps back (using fseek(fp, -2, SEEK_CUR)) to read the previous character.
This seems to be ok if the file has a single line (i.e. no new line character). The above logic fails if it encounters a new line character and gets into an infinite loop priting a series of new-line character.
To fix this I checked for the character read and if it is new-line character, I move the file pointer by 3 steps (fseek(fp, -3, SEEK_CUR)) and now the logic works fine.
Can anyone please explain me why a this special consideration for a new-line character.
Many Thanks in advance.
Thanks
Praveen 20 33018
sahukar praveen wrote: Part 1.1 Type: Plain Text (text/plain) Encoding: quoted-printable
Please do not post html or attachments in c.l.c.
--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
"sahukar praveen" <sa************ @yahoo.co.in> wrote in message news:<3f******@ usenet01.boi.hp .com>... Hello,
I have a question.
I try to print a ascii file in reverse order( bottom-top). Here is the logic.
1. Go to the botton of the file fseek(). move one character back to avoid the EOF. 2. From here read a character, print it, move the file pointer (FILE*) to 2 steps back (using fseek(fp, -2, SEEK CUR)) to read the previous character.
This seems to be ok if the file has a single line (i.e. no new line character). The above logic fails if it encounters a new line character and gets into an infinite loop priting a series of new-line character.
To fix this I checked for the character read and if it is new-line character, I move the file pointer by 3 steps (fseek(fp, -3, SEEK CUR)) and now the logic works fine.
Can anyone please explain me why a this special consideration for a new-line character.
Many Thanks in advance.
Thanks Praveen --
Some platforms represent a newline with a carriage return and line
feed pair, rather than a single newline character, which is why you
need to back up three characters instead of two.
Instead of reading a single character at a time, you might want to
grab a chunk of characters into a buffer, then print from that buffer.
For one thing, it reduces the number of calls to fseek() (which may
be a fairly expensive operation), and you can just skip over the
characters you don't want to print.
On Tue, 25 Nov 2003 16:38:48 +0530, in comp.lang.c , "sahukar praveen"
<sa************ @yahoo.co.in> wrote: Hello,
I have a question.
I try to print a ascii file in reverse order( bottom-top).
A quicker way if you have enugh memory would be to malloc a block of
memory you think is large enough for the entire file, fread() the file
into it, go to the last byte and walk backwards through the block.
PLatform specific extensions would help you find how much memory you
needed.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
Mark McIntyre <ma**********@s pamcop.net> wrote in message : A quicker way if you have enugh memory would be to malloc a block of memory you think is large enough for the entire file, fread() the file into it, go to the last byte and walk backwards through the block. PLatform specific extensions would help you find how much memory you needed.
The solution I could think of printing the file in reverse order
without attempting to know the size of the file was a recursive one.
But I think this solution might choke on large files. This recursive
solution is equivalent to pushing characters on a stack and then
popping them, I think reading more than one character at a time would
led to faster code.
#include <stdio.h>
#include <stdlib.h>
/*print the characters of the file in reverse order*/
void rev_file_c(FILE *fp)
{
int c;
c=fgetc(fp);
if(c==EOF) return;
rev_file_c(fp);
putchar(c);
}
#define MAX_LINE_SIZE 4096
/*print the lines of the file in reverse order*/
void rev_file_lin(FI LE *fp)
{
char buf[MAX_LINE_SIZE];
char *s;
s=fgets(buf,siz eof buf,fp);
if(NULL==s)
{
if(ferror(fp))
{
perror(NULL);
exit(EXIT_FAILU RE);
}
else return;
}
rev_file_lin(fp );
fputs(buf,stdou t);
}
int
main(void)
{
FILE *fp;
fp=fopen("c:\\t emp\\rev_file.c ","r");
if(NULL == fp)
{
perror(NULL);
return 1;
}
rev_file_c(fp);
fclose(fp);
return 0;
}
--------
Jai Hind!
Vande Mataram.
Debashish Chakravarty wrote: Mark McIntyre <ma**********@s pamcop.net> wrote in message :
A quicker way if you have enugh memory would be to malloc a block of memory you think is large enough for the entire file, fread() the file into it, go to the last byte and walk backwards through the block. PLatform specific extensions would help you find how much memory you needed.
The solution I could think of printing the file in reverse order without attempting to know the size of the file was a recursive one. But I think this solution might choke on large files. This recursive solution is equivalent to pushing characters on a stack and then popping them, I think reading more than one character at a time would led to faster code.
Try this one. I would write a few things differently today, and
there is an insect in revstring, which won't get triggered here.
/* Routines to reverse a file, char by char. */
/* by C.B. Falconer, 19 Dec. 2001 */
/* Released to public domain. Attribution appreciated */
/* Known bugs - A file without an initial empty line */
/* will have one added. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLN 256
typedef struct line {
char *ln;
struct line *next;
} line, *lineptr;
/* =============== =============== ========= */
/* reverse string in place. Return length */
size_t revstring(char *string)
{
char *last, temp;
size_t lgh;
lgh = strlen(string);
last = string + lgh; /* points to '\0' */
while (last-- > string) {
temp = *string; *string++ = *last; *last = temp;
}
return lgh;
} /* revstring */
/* =============== ========== */
/* Reverse file, end to end */
int main(void)
{
char buffer[MAXLN];
lineptr p, last;
size_t lgh;
p = last = NULL;
while (fgets(buffer, MAXLN, stdin)) {
lgh = revstring(buffe r);
if (p = malloc(sizeof (line))) {
p->next = last;
if (p->ln = malloc(lgh + 1)) {
strcpy(p->ln, buffer);
last = p;
}
else {
free(p);
break;
}
}
else break;
}
p = NULL;
while (last) {
free(p);
fputs(last->ln, stdout);
p = last;
last = last->next;
}
if (p && ('\n' != p->ln[strlen(p->ln) - 1]))
fputc('\n', stdout);
free(p);
return 0;
} /* main */
--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
CBFalconer <cb********@yah oo.com> wrote in message news:<3F******* ********@yahoo. com>... Debashish Chakravarty wrote: Mark McIntyre <ma**********@s pamcop.net> wrote in message :
A quicker way if you have enugh memory would be to malloc a block of memory you think is large enough for the entire file, fread() the file into it, go to the last byte and walk backwards through the block. PLatform specific extensions would help you find how much memory you needed.
The solution I could think of printing the file in reverse order without attempting to know the size of the file was a recursive one. But I think this solution might choke on large files. This recursive solution is equivalent to pushing characters on a stack and then popping them, I think reading more than one character at a time would led to faster code.
Try this one. I would write a few things differently today, and there is an insect in revstring, which won't get triggered here.
/* Routines to reverse a file, char by char. */ /* by C.B. Falconer, 19 Dec. 2001 */ /* Released to public domain. Attribution appreciated */
/* Known bugs - A file without an initial empty line */ /* will have one added. */
#include <stdio.h> #include <string.h> #include <stdlib.h>
#define MAXLN 256
typedef struct line { char *ln; struct line *next; } line, *lineptr;
/* =============== =============== ========= */ /* reverse string in place. Return length */ size_t revstring(char *string) { char *last, temp; size_t lgh;
lgh = strlen(string); last = string + lgh; /* points to '\0' */ while (last-- > string) { temp = *string; *string++ = *last; *last = temp; } return lgh; } /* revstring */
/* =============== ========== */ /* Reverse file, end to end */ int main(void) { char buffer[MAXLN]; lineptr p, last; size_t lgh;
p = last = NULL; while (fgets(buffer, MAXLN, stdin)) { lgh = revstring(buffe r); if (p = malloc(sizeof (line))) { p->next = last; if (p->ln = malloc(lgh + 1)) { strcpy(p->ln, buffer); last = p; } else { free(p); break; } } else break; } p = NULL; while (last) { free(p); fputs(last->ln, stdout); p = last; last = last->next; } if (p && ('\n' != p->ln[strlen(p->ln) - 1])) fputc('\n', stdout); free(p); return 0; } /* main */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static unsigned int byte_count(FILE *);
static void reverse_file(ch ar *, unsigned int);
int main(int argc, char **argv)
{
char *ptr;
unsigned int size;
FILE *fp;
if(argc < 2)
printf("%s <file>\n", argv[0]);
if(!(fp = fopen(argv[1], "r")))
return EXIT_FAILURE;
size = byte_count(fp);
if(!(ptr = malloc(size+1)) )
return EXIT_FAILURE;
ptr[size] = '\0';
fread(ptr, size, sizeof(char), fp);
fclose(fp);
reverse_file(pt r, size);
return EXIT_SUCCESS;
}
static unsigned int byte_count(FILE *fp)
{
int c;
unsigned int count = 0;
while((c = fgetc(fp)) != EOF)
++count;
rewind(fp);
return count;
}
static void reverse_file(ch ar *base, unsigned int size)
{
char *end = &base[size-1];
if(*end == '\n') {
*end = '\0';
--end;
}
for( ; end >= base; --end)
if(*end == '\n') {
*end = '\0';
printf("%s\n", end+1);
}
printf("%s\n", base);
free(base);
}
I think my version might outperform yours.
fgets is kind of slow on large files.
--
nethlek
Mantorok Redgormor wrote:
.... snip ... I think my version might outperform yours. fgets is kind of slow on large files.
I believe it doesn't do the same thing. In addition I doubt that
reading a file twice can be faster than reading it once.
--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
On Thu, 27 Nov 2003 08:07:47 GMT,
CBFalconer <cb********@yah oo.com> wrote: Mantorok Redgormor wrote: ... snip ... I think my version might outperform yours. fgets is kind of slow on large files.
I believe it doesn't do the same thing. In addition I doubt that reading a file twice can be faster than reading it once.
Not to mention that reading the entire contents of a huge file into memory
is not exactly the best thing to do. But of course having gigabytes of
real memory available will surely help.
Villy
Villy Kruse wrote: CBFalconer <cb********@yah oo.com> wrote: Mantorok Redgormor wrote: ... snip ... I think my version might outperform yours. fgets is kind of slow on large files.
I believe it doesn't do the same thing. In addition I doubt that reading a file twice can be faster than reading it once.
Not to mention that reading the entire contents of a huge file into memory is not exactly the best thing to do. But of course having gigabytes of real memory available will surely help.
Inasmuch as my version also reads everything into memory, I didn't
consider that a valid objection :-) However the response to
memory allocation failure is also different.
--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Erik Andersson |
last post by:
Hi!
I need to read a file (line-by-line) in reverse order, without reading the
whole file into memory first.
Is there an easy way of doing this? As in, is there a PHP function I could
use?
The solution has to be platform independent, so "popen("tac $filename")...
wouldn't work.
|
by: James Lee |
last post by:
I am doing a simple query like col1, col2, date, col4 from table1.
All four colums are of type blob. For date column, I store a string
like this:
Fri Feb 13 11:01:24 2004
I store records as they come in so the oldest record is at the top of
the table. When I select and display, I want to display them in
reverse order (newest record at...
|
by: vijay |
last post by:
Hello,
As the subject suggests, I need to print the string in the reverse
order. I made the following program:
# include<stdio.h>
struct llnode
{
char *info;
|
by: Fabio Cannizzo |
last post by:
Is it possible to do something similar to the STL iterators, i.e. to execute
a foreach loop in reverse order?
Thanks,
Fabio
|
by: aatish19 |
last post by:
1: Write a program that asks the user to input an integer value and
print it in a reverse order
Sample Output
Enter any number 65564
Reverse of 65564 is 46556
2: Write a program that takes a string as an input and print it in
reverse order.(don't use bulit-in/library function).
Sample Output
Enter any string: i m Kashif
| |
by: thrill5 |
last post by:
I have an xml document such as:
<device>
<element>first</element>
<element>second</element>
</device>
I am using this as the source for an xslt transform that goes like
<xsl:for-each select="/device/element>
This is the <xsl:value-of select="."/> element.
|
by: srp8982 |
last post by:
hello,
I need help (code) on following program ,its in c...
1)allow user to write file name in command line, read the file...
2) count characters, spaces and no. of lines in file given...
3)read upto first 10 lines, and print them in reverse order
thanking you in advance
|
by: aburningflame23 |
last post by:
alright this is my problem.....please help
i need to write a program that reads 10 integers from a file into an array and then prints out the numbers in reverse order. It also prints out the greatest number, smallest number, and the average
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |