tags:

views:

373

answers:

2

I am passing a string as an argument to my program and extracting its position in a text file. Can we read a text file only upto this certain position in C?? If yes, then please tell me how.

+2  A: 

Just use fread() up to the number of bytes that puts you to that "position" in the file. For example, if you know you want to read up to the position at 1928 bytes, just read that many bytes in with fread.

Reed Copsey
Thanks for the answer....But is there a way to read from one file and write to another file directly without reading into a buffer??
Light_handle
No. You always have to work through a buffer. It can be a very samll buffer, though - just read a small number of bytes, and write it into the other file in a loop.
Reed Copsey
Thank you very much..
Light_handle
+1  A: 

What you need is the strstr function written for file handles. This is a generic implementation of strstr. You can pretty easily modify it to use file buffers instead of another string, so I won't do your work for you :P

char *
strstr(const char *haystack, const char *needle)
{
        char c, sc;
        size_t len;

        if ((c = *needle++) != '\0') {
                len = strlen(needle);
                do {
                        do {
                                if ((sc = *haystack++) == '\0')
                                        return (NULL);
                        } while (sc != c);
                } while (strncmp(haystack, needle, len) != 0);
                haystack--;
    }
        return ((char *)haystack);
}
Charles Ma
just to be slightly more idiomatic:-use argument names 'haystack' and 'needle' respectively-use null char character rather than 0 constant ((c = *find++) != '\0')
David Claridge
Hmm....Thanks..
Light_handle