Skip to content

Instantly share code, notes, and snippets.

@marvhus
Last active June 26, 2024 15:50
Show Gist options
  • Save marvhus/546cc0062b77674c9c6879d6d559b9a0 to your computer and use it in GitHub Desktop.
Save marvhus/546cc0062b77674c9c6879d6d559b9a0 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
printf("Error: Failed to open file %s\n", argv[1]);
return 1;
}
fseek(file, 0L, SEEK_END);
size_t file_size = ftell(file);
fseek(file, 0L, SEEK_SET);
char *data = malloc(sizeof(char) * file_size);
fread(data, 1, file_size, file);
size_t count = 0;
for (char *end = data + file_size; data != end; data++)
if (*data == '\n') count++;
fclose(file);
printf("%zu\n", count);
return 0;
}
# write is for writing N newlines to a file.
# count is from counting the newlines in a file.
CC := gcc
CFLAGS := -Wall -Wextra -Werror \
-std=c11 -pedantic
TARGETS := count \
write
.PHONY: all
all: $(TARGETS)
%: %.c
$(CC) $< -o $@ $(CFLAGS)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc != 3) {
printf("Usage: %s <file> <line count>\n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "w");
if (file == NULL) {
printf("Error: Failed to open file %s\n", argv[1]);
return 1;
}
long long line_count = atoi(argv[2]);
char *data = malloc(sizeof(char) * line_count);
memset(data, '\n', line_count);
fwrite(data, 1, line_count, file);
fclose(file);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment