Mohamed_37 0 Newbie Poster
#include <stdio.h>
#include <stdlib.h>                            
#include <string.h>

#include "memo_list.h"

void shownotes(Memo item);
char * s_gets(char * st, int n);

int main()
{
    List Notes;
    Memo temp;

    FILE *wfile,*sfile,*lfile,*rfile;

    char ch;
    char *line ;



    /* initialize */
    InitializeList(&Notes);
    /*check IsFull? */
    if (ListIsFull(&Notes))
    {
     fprintf(stderr,"No memory available! Bye!\n");
     exit(1);
    }

puts("Enter char from {w,s,l,r}");
puts("for Memo Title to be stored:\n");                    
puts("w:#Work ---------- s:#Self");
puts("l:#Life ---------- r:#Relision\n");
puts("Enter 'q' to stop receiving!");
scanf("%c",&ch);                                                    

 while (ch!='q')
 {

    switch(ch)
    {
        case 'w' ://#Work

                  if((wfile =fopen("Work.txt","a+")) == NULL) 
                    {
                      fprintf(stderr,"Can't open %s\n", "#Work file");      
                      exit(EXIT_FAILURE);                    
                    }
                 /*Store selected data in title member and prober file */
                strcpy(temp.title,"#work");
                fprintf(wfile,"%50s\n",temp.title );

                break;
                /*-------------------------------------*/
                case 's' :  //#Self

                        if((sfile =fopen("Self.docx","a+")) == NULL) 
                           {
                             printf("Can't open %s\n", "#Self file");      
                             exit(EXIT_FAILURE);                   
                           }
                           strcpy(temp.title,"#Self");
                           fprintf(sfile, temp.title );

                           break;
                /*-------------------------------------*/
                case 'l' :  //#Life

                          if((lfile =fopen("Life.docx","a+")) == NULL) 
                          {
                           printf("Can't open %s\n", "#Life file");      
                           exit(EXIT_FAILURE);                    
                          }
                          strcpy(temp.title ,"#Life");
                          fprintf(lfile, temp.title );

                          break;
                /*-------------------------------------*/
                case 'r' :    //#Relision

                          if((rfile =fopen("Relision.docx","a+"))==NULL)
                          {
                            printf("Can't open %s\n", "#Relision file");     
                            exit(EXIT_FAILURE);                    
                           }
                          strcpy(temp.title,"#Relision");
                          fprintf(wfile, temp.title );

                          break;
             /*-------------------------------------*/
                default :
                         puts("Enter acceptable choice!");
                         break;
            }



 puts("Enter Memo Text to store:\n");
 temp.text=s_gets(line,1000);
 if(temp.text!=NULL)
 {

    fprintf(wfile,"%1000s",line  );
    fflush(wfile);

puts("Enter char from {w,s,l,r}");
puts("for next Memo Title to be stored:\n");                     
puts("w:#Work ---------- s:#Self");
puts("l:#Life ---------- r:#Relision\n");
puts("Enter 'q' to stop receiving!");
scanf("%c",&ch);


 if (AddItem(temp,&Notes)==false)
             {
             fprintf(stderr,"Problem allocating memory\n");
              exit(1);
             }
 }
 }

if(ListIsEmpty(&Notes))
{
 printf("No data entered. ");

}else
{
 printf ("Here is the Notes list:\n");
 Traverse(&Notes, shownotes);
}

printf("\nDone!\n");


if (fclose(lfile) != 0 || fclose(wfile) != 0 || fclose(sfile) != 0 || fclose(rfile) != 0)
{
 printf("Error in closing file!\n");  //user alert message to screen
}


return 0;                                
}


void shownotes(Memo item)
{
printf("Title: %50s \nText: %500s\n", item.title,item.text);
}


char * s_gets(char * st, int n)
{

char * ret_val;
char * find;
ret_val = fgets(st, n, stdin);
if (ret_val)
  {
   find = strchr(st, '\n'); // look for newline
   if (find) // if the address is not NULL,
      *find = '\0'; // place a null character there
   else

     while (getchar() != '\n')
            continue; // dispose of rest of line
   }

   return ret_val;
   }

I am trying to store titled notes about many subjects
but I have problem with the reading function and may be
also the order of the conditional & looping control statments
I hope someone can help.

Dani AI

Generated

— core causes and a compact fix.

Primary problems found: the input buffer pointer is never allocated (calling fgets on an uninitialized char * is undefined). The code always writes memo text to the same file pointer instead of the file chosen by the user, and one branch even writes to the wrong pointer. fprintf is used without a format string (format-string vulnerability). scanf("%c") is used in a way that leaves the newline in the input stream, and file pointers are closed unconditionally even when not opened. Finally, if the list stores pointers (rather than copying strings), the code stores pointers to a temporary buffer that gets overwritten — this causes stale/garbage text in the list.

A concise, safer pattern (reads choice with fgets, uses a single target FILE*, trims the newline, writes with a format string, allocates text before adding to the list):

char choicebuf[8];
char buf[1024];
FILE *out = NULL;

while (fgets(choicebuf, sizeof choicebuf, stdin)) {
  char ch = choicebuf[0];
  if (ch == 'q') break;

  const char *fname = NULL;
  const char *title = NULL;
  if (ch == 'w') { fname = "Work.txt"; title = "#Work"; }
  else if (ch == 's') { fname = "Self.txt"; title = "#Self"; }
  else if (ch == 'l') { fname = "Life.txt"; title = "#Life"; }
  else if (ch == 'r') { fname = "Religion.txt"; title = "#Religion"; }
  else { puts("Invalid choice"); continue; }

  out = fopen(fname, "a");
  if (!out) { perror(fname); continue; }

  puts("Enter memo text:");
  if (!fgets(buf, sizeof buf, stdin)) { fclose(out); break; }
  buf[strcspn(buf, "\n")] = '\0';   /* remove trailing newline */

  fprintf(out, "%s\n%s\n", title, buf);
  fclose(out);

  Memo m;
  strncpy(m.title, title, sizeof m.title);
  m.title[sizeof m.title - 1] = '\0';
  m.text = strdup(buf);             /* allocate a copy for the list */
  if (m.text == NULL) { perror("malloc"); continue; }
  AddItem(m, &Notes);
}

Checklist summary: declare a real buffer (not char *), use fgets (or scanf(" %c", &ch) with a leading space) for choices, always use fprintf(file, "%s", str) not fprintf(file, str), open/write/close the same FILE per category, initialize FILE pointers to NULL and only fclose non-NULL pointers, and ensure any stored text is dynamically allocated (or that AddItem makes its own copies). Free allocated text when removing list items to avoid leaks.

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.