0

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.

DaveR
  • 9,540
  • 3
  • 39
  • 58
Light_handle
  • 3,947
  • 7
  • 29
  • 25
  • 3
    Your question is not totally clear - it might be easier if you could post some of the source of your current program. Also, what do you mean by 'certain position' - a specific number of characters, or after you find a given character(s)? – DaveR Aug 09 '09 at 23:00
  • Yeah...I mean upto the position where the string exists in the file. – Light_handle Aug 10 '09 at 00:16

2 Answers2

3

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
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 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 Aug 10 '09 at 00:07
  • 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 Aug 10 '09 at 00:29
1

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
  • 47,141
  • 22
  • 87
  • 101
  • 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 Aug 10 '09 at 00:31