Hi. I'm having problems about my program. My program is something like a directory. It takes in values for different fields and stores it in a linked list in a sorted manner. It also allows the user to save the linked list contents to a text file. Everything runs okay except for the function that checks the file existence and if it exists, it reads the file and stores its contents to a linked list before inserting the new node which contains the recent user-input.

Here is my copyFiletoList and insert function:

void copyFiletoList(nodePtr *start){

    nodePtr newPtr, prevPtr, curPtr;
    RecordNode temp;
    nodePtr fPtr;
    char lN[30]="\0";
    char fN[30]="\0";
    char mN[30]="\0";
    char cE[30]="\0";
    char sN[30]="\0";
    char cN[30]="\0";

    fp = fopen("directory.txt", "r");

    fPtr = *start;
    rewind(fp);

    while(!feof(fp)){

        fread(&temp, (sizeof(struct recordNode)-1), 1, fp);
            fscanf(fp," %[^\n] %[^\n] %[^\n] %[^\n] %[^\n] %[^\n]", temp.Name, temp.fName, temp.mName, temp.course, temp.sNum, temp.cNum);
        insert(&fpTr, temp.Name, temp.fName, temp.mName, temp.course, temp.sNum, temp.cNum);

        }

    fclose(fp);
}

void insert(nodePtr *start, char lName[30], char f[30], char m[30], char c[30], char s[10], char cN[10]){

    nodePtr newPtr, prevPtr, curPtr;

    newPtr = malloc(sizeof(struct recordNode));

    if(newPtr != NULL){

        strcpy(newPtr->Name, lName);
        strcpy(newPtr->fName, f);
        strcpy(newPtr->mName, m);
        strcpy(newPtr->course, c);
        strcpy(newPtr->sNum, s);
        strcpy(newPtr->cNum, cN);
        newPtr->nextPtr = NULL;

        prevPtr = NULL;
        curPtr = *start;

        while(curPtr!=NULL && strcmp(lName,curPtr->Name)==1){
            prevPtr = curPtr;
            curPtr = curPtr->nextPtr;
        }

        if(prevPtr == NULL){
            /*Insert at the beginning*/
            newPtr->nextPtr = *start;
            *start = newPtr;
        }
        else{
            /*Insert at the middle*/
            prevPtr->nextPtr = newPtr;
            newPtr->nextPtr = curPtr;
        }
    }else{
        printf("Memory insufficient. Cannot insert.\n");
    }
}

The whole program compiles and runs fine without any error, but when I try to display the whole linked list, it only displays the recent data from input even though the file already has contents prior to the run. Please help me. Thank you.

Dani AI

Generated

Quick summary and final takeaways (resolved by using fscanf, with an early tip from about checking fopen): the symptom — a file that clearly contains records but only the newest input shows in the list — typically comes from a small set of predictable bugs visible in the original code.

Concrete problems observed

  • Mixing binary and text reads: calling fread() then fscanf() on the same stream moves the file position unpredictably and is the wrong approach for a text file.
  • Wrong fread size: using sizeof(struct recordNode) - 1 is almost certainly incorrect.
  • Using while(!feof(fp)) is brittle; it often leads to one extra failed iteration.
  • Wrong string comparison: strcmp() returns negative / zero / positive, not the literal 1 — using strcmp(...) == 1 will fail in most cases.
  • Inconsistent variable names (fPtr vs fpTr) suggests the wrong pointer might have been passed to insert(), so earlier records were never added to the same list head.

Practical, robust fixes

  • Always check fopen() for NULL (as noted by ) and do not call rewind() immediately after fopen().
  • Drive the loop by the read routine return value, e.g. test fscanf() or fgets()/sscanf() results instead of feof().
  • Use width limits in scanf conversions to avoid buffer overflow (for example %29[^\n] for a 30-byte buffer).
  • Do not mix fread (binary) and fscanf (text) on the same file. Pick one style and keep file format consistent.
  • Use correct ordering tests like strcmp(lName, curPtr->Name) > 0 to walk the list. Initialize the list head to NULL and pass the correct head pointer into insert(). Use malloc(sizeof *newPtr) and check its return.

Extra notes
For fields that may contain spaces, prefer reading lines with fgets() and parsing with sscanf() or a tokenizer, or use a simple CSV/delimited format. Guard against blank lines and check every function return value to make file-to-list copying reliable and safe.

Recommended Answers

All 3 Replies

Your program is not checking for the existance if the file, it just assumes the file always exists. You need to check for NULL return from fopen() and do nothing if NULL was returned.

BTW: Don't call rewind() after fopen() because its a waste of effort, the file pointer is already at the beginning of the file.

I call the function after checking for the file existence. So it only does it to copy the contents. What I am after is why does this function does not seem to copy anything at all hence only the recent user input is the content of the linked list.

Finally got to solve my problem. I used fscanf instead. Thanks for the help.

 if((fp = fopen("directory.txt", "r"))!=NULL){
            printf("-------------------------\n::FILE EXISTENCE CHECK::\n-------------------------\n");
            printf("File: directory.txt exists. Copying file contents...\n");

            while(!feof(fp)){
                    if(fscanf (fp, " %[^\n] %[^\n] %[^\n] %[^\n] %[^\n] %[^\n]", lastName, firstName, midName, course, studNum, contactNum) != EOF){
                        insert(&sPtr, lastName, firstName, midName, course, studNum, contactNum);
                    }else{
                        break;
                    }
            }

            printf("File contents copied. \n\n");
            fclose(fp);

        }else{
            printf("--------------------------\n ::FILE EXISTENCE CHECK::\n--------------------------\n");
            printf("File: directory.txt does not exist.\n\n");
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.