cut: Accept input from stdin if no files are given

This commit is contained in:
Matthew Olsson 2020-07-02 17:59:25 -07:00 committed by Andreas Kling
parent 4c48c9d69d
commit 6cb6e47779
Notes: sideshowbarker 2024-07-19 05:13:18 +09:00

View file

@ -164,13 +164,14 @@ static void expand_list(Vector<String>& tokens, Vector<Index>& indexes)
static void cut_file(const String& file, const Vector<Index>& byte_vector) static void cut_file(const String& file, const Vector<Index>& byte_vector)
{ {
FILE* fp = nullptr; FILE* fp = stdin;
if (!file.is_null()) {
fp = fopen(file.characters(), "r"); fp = fopen(file.characters(), "r");
if (!fp) { if (!fp) {
fprintf(stderr, "cut: Could not open file '%s'\n", file.characters()); fprintf(stderr, "cut: Could not open file '%s'\n", file.characters());
return; return;
} }
}
char* line = nullptr; char* line = nullptr;
ssize_t line_length = 0; ssize_t line_length = 0;
@ -195,6 +196,8 @@ static void cut_file(const String& file, const Vector<Index>& byte_vector)
if (line) if (line)
free(line); free(line);
if (!file.is_null())
fclose(fp); fclose(fp);
} }
@ -227,12 +230,16 @@ int main(int argc, char** argv)
} }
} }
if (files.is_empty() || byte_list == "") if (byte_list == "")
print_usage_and_exit(1); print_usage_and_exit(1);
Vector<Index> byte_vector; Vector<Index> byte_vector;
expand_list(tokens, byte_vector); expand_list(tokens, byte_vector);
quick_sort(byte_vector, [](auto& a, auto& b) { return a.m_from < b.m_from; }); quick_sort(byte_vector, [](auto& a, auto& b) { return a.m_from < b.m_from; });
if (files.is_empty())
files.append(String());
/* Process each file */ /* Process each file */
for (auto& file : files) for (auto& file : files)
cut_file(file, byte_vector); cut_file(file, byte_vector);