I want my code to ask user if he/she wants to either add text by using void add() or delete a line by using void delrow() after void list() works, but the code performs both add() and delrow() after asking it. How should I use the switch statement?
Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME_SIZE 128
#define MAX_LINE 2048
void list(){ // Printing the list.
char filename[100];
printf("\n*** TODO List ***\n ");
FILE *fptr ;
printf("\nPlease enter the file name with its extension: ");
scanf("%s", filename);
fptr = fopen(filename, "r");
char ch[100]; // Character limit.
while(fgets(ch,sizeof(ch),fptr)){
printf("%s",ch);
}
}
void add(){ // Adding text to list.
char todo[150]; // Character limit.
char filename[100];
FILE *fptr ;
printf("\n***TODO List - Add ToDo***\n ");
printf("\nPlease enter the file name with its extension:");
scanf("%s", filename);
fptr = fopen(filename, "a");
printf("\nEnter todo:"); // Getting the text.
scanf("%s",todo);
fprintf(fptr,"\n%s",todo); // Importing the text.
}
void delrow(){
printf("\n***TODO List - Delete Rows***\n ");
FILE *fileptr1, *fileptr2;
char filename[40];
// File name limit
char ch;
int delete_line, temp = 1;
printf("\nPlease enter the file name with its extension: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" \n Please enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("temp", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file temporary to original name
rename("temp", filename);
printf("\n The contents of file after being modified are as follows:\n");
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
}
int main(void) {
int choice=0;
list();
printf("\nPlease state if you want to add todo or delete an existing todo (1:add 2:delete): ");
scanf("%d",&choice);
switch(choice){
case 1:
add();
case 2:
delrow();
default:
printf("\nUnacceptable choice.");
}
return 0;
}
You must add break
statements or your cases will fall through to the one below.
switch (choice) {
case 1:
add();
break;
case 2:
delrow();
break;
default:
printf("\nUnacceptable choice.");
}