0

I have a character buffer - char buff[1000], and am trying to use strncpy to read the first 16 characters and store it as part of a list, and then read the next 24 characters and store it as another part of the list. However, when i call strncpy twice, the second strncpy goes back to the beginning of the buffer rather than where I left off after the first strncpy.

        char buff[1000];
 14     struct List list;
 15     initList(&list);
 16 
 17     struct Node *node = NULL;
 18     while (!feof(myf) == 1){
 19         fread(buff, 40, 1, myf);
 20         struct MdbRec *newRec;
 21         newRec = (struct MdbRec *)malloc(sizeof(struct MdbRec));
 22         if (newRec == NULL){
 23            exit(1);
 24         }
 25         strncpy(newRec->name, buff, 16);
 26         strncpy(newRec->msg, buff, 24);
 27 
 28         node = addAfter(&list, node, newRec);

How do I fix this? Thanks!!!

lurker
  • 56,987
  • 9
  • 69
  • 103
  • That's just how `stncpy` works. It doesn't automatically modify your buffer pointer and advance it. Since you aren't passing its address, it couldn't anyway. Did you read the documentation on the function? Your second string copy could be done as, `strnpy(newRec->msg, buff+16, 24);` if you want to advance 16 chars into `buff`. – lurker Mar 11 '14 at 01:21
  • You might also want to read this: http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong/5432517#5432517 – lurker Mar 11 '14 at 01:27
  • 1
    And this: http://the-flat-trantor-society.blogspot.com/2012/03/no-strncpy-is-not-safer-strcpy.html – Keith Thompson Mar 11 '14 at 02:34
  • Don't use `feof()` to detect end-of-file, and don't compare the result to 1. Check the value returned by `fread()` instead. – Keith Thompson Mar 11 '14 at 02:38

1 Answers1

1

You need to increment the pointer:

while (!feof(myf) == 1){
   fread(buff, 40, 1, myf);
   ...
   char *p = buff;
   strncpy(newRec->name, p, 16);
   p += 16;
   strncpy(newRec->msg, p, 24);
   ...

... or ...

while (!feof(myf) == 1){
   fread(buff, 40, 1, myf);
   ...
   int i=0;
   strncpy(newRec->name, &buff[i], 16);
   i += 16;
   strncpy(newRec->msg, &buff[i], 24);
   ...
FoggyDay
  • 11,962
  • 4
  • 34
  • 48