Question

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!!!

Était-ce utile?

La solution

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);
   ...
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top