/* * Copyright 2014 (c) Anna Schumaker. * Do stuff with files * * Usage: files -D|-L [-c -g -o {R, W, N} -O -r -v -w] name [DATA] * * -D: FILE_TYPE_DATA * -L: FILE_TYPE_LEGACY * * -c: Test closing the file * -g: Read file using getline() * -o: Open the file for READ, WRITE, or NOT_OPEN * -O: Open the file a second time * -r: Read data from file * -v: Print version and exit * -w: Write data to file * */ #include #include #include enum action_t { CLOSE, OPEN, PATHS, READ, VERSION, WRITE }; int print_version(File &f) { print("%u\n", f.get_version()); return 0; } int print_filepath(File &f) { print("%s\n", f.get_filepath()); return 0; } int open_file(File &f, OpenMode mode) { try { f.open(mode); return 0; } catch (int err) { return err; } } int main(int argc, char **argv) { int c, ret; action_t action = PATHS; FileLocHint hint = FILE_TYPE_INVALID; OpenMode mode = NOT_OPEN; bool second_open = false; bool getline = false; std::string file; std::string data; while ((c = getopt(argc, argv, "cDgLo:Orvw")) != -1) { switch (c) { case 'c': action = CLOSE; break; case 'D': hint = FILE_TYPE_DATA; break; case 'g': getline = true; break; case 'L': hint = FILE_TYPE_LEGACY; break; case 'o': action = OPEN; switch (optarg[0]) { case 'R': mode = OPEN_READ; break; case 'W': mode = OPEN_WRITE; break; case 'N': mode = NOT_OPEN; break; default: print("Invalid open mode\n"); return 1; } break; case 'O': second_open = true; break; case 'r': action = READ; break; case 'v': action = VERSION; break; case 'w': action = WRITE; break; default: return 1; } } if (optind < argc) file = argv[optind++]; if (optind < argc) data = argv[optind++]; File f(file, hint); switch (action) { case CLOSE: ret = open_file(f, OPEN_WRITE); if (ret == 0) { f.close(); ret = open_file(f, OPEN_WRITE); } return ret; case OPEN: ret = open_file(f, mode); if ((ret == 0) && (second_open == true)) ret = open_file(f, mode); return ret; case PATHS: return print_filepath(f); case READ: ret = open_file(f, OPEN_READ); if (ret == 0) { do { if (getline == true) data = f.getline(); else f >> data; if (f.good() == false) break; print("%s\n", data.c_str()); } while (true); } return ret; case VERSION: return print_version(f); case WRITE: ret = open_file(f, OPEN_WRITE); if (ret == 0) f << data << std::endl; return ret; } }