I have this code:
#include <unistd.h>
#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
void add(char todo[], string priority, string home){
FILE *file;
file = fopen(home.c_str(), "a");
fprintf(file, "%-50s| %-6s\n", todo, priority.c_str());
fclose(file);
}
void list(string home){
string line;
fstream file(home.c_str(),ios::in);
int i = 0;
if (file.is_open()){
while( getline( file, line ) ) {
cout << "[" << i << "] " << line << '\n';
i++;
}
}
file.close();
}
void clear(string home){
FILE *file;
file = fopen(home.c_str(), "w");
fprintf(file, "");
fclose(file);
}
void remove(string home, int n){
string f;
string line;
fstream file(home.c_str(),ios::in);
int i = 0;
if (file.is_open()){
while( getline( file, line ) ) {
if (i != n){
cout << i << '\n' << n << '\n';
files += line;
files += '\n';
}
i++;
}
}
file.close();
clear(home);
fstream fileo(home.c_str(),ios::out);
fileo << f;
}
void help(){
cout << "Usage:\n";
cout << "\tt-do [options]\n";
cout << "Options\n";
cout << "\t-a [TODO]\n";
cout << "\t\tAdd a todo with summary TODO\n";
cout << "\t-l\n";
cout << "\t\tList TODOs\n";
cout << "\t-c\n";
cout << "\t\tClear all TODOs\n";
}
int main (int argc, char* argv[]) {
string home(getenv("HOME"));
string todo = "/.todo.txt";
string priority = "Medium";
home = home + todo;
int opt;
int n;
while ((opt = getopt(argc,argv, "a:p:f:rlhc")) !=EOF ){
switch (opt){
case 'a':
add(optarg, priority, home);
break;
case 'l':
list(home);
break;
case 'c':
clear(home);
break;
case 'r':
n = atoi(optarg);
remove(home, n);
break;
case 'h':
help();
break;
case '?':
help();
break;
}
}
return 0;
}
when run with -r it should remove a line that the user specified, eg:
$t-do -r 1 #Should remove the first line
but it produces a segfault