Skip to content

Instantly share code, notes, and snippets.

@MisterDA
Last active October 28, 2016 23:28
Show Gist options
  • Save MisterDA/ebddbf7058217a925af7ea72e523dd38 to your computer and use it in GitHub Desktop.
Save MisterDA/ebddbf7058217a925af7ea72e523dd38 to your computer and use it in GitHub Desktop.
SC5 - TD6 - Exo4 - Q7
#include "copy.h"
static int count_lines(FILE *in) {
int cur = -1, prev, lines = 0;
do {
prev = cur;
cur = fgetc(in);
if (cur == '\n')
++lines;
} while (cur != EOF);
if (prev != '\n' && lines)
++lines;
return lines;
}
static int digits(int i) {
int d = 0;
do {
i /= 10;
++d;
} while (i != 0);
return d;
}
void copy(FILE *in, FILE *out) {
int lines = count_lines(in);
rewind(in);
char *line = NULL;
size_t len = 0;
ssize_t read;
int space_len = digits(lines);
int i = 0;
long open = -1, close = -1;
while ((read = getline(&line, &len, in)) != -1) {
if (strstr(line, "||:") == line) {
open = ftell(in) - read;
} else if (strstr(line, ":||") == line + read - 4 && close != ftell(in)) {
close = ftell(in);
fseek(in, open, SEEK_SET);
}
fprintf(out, "%*d %s", space_len, ++i, line);
}
free(line);
}
#ifndef COPY_H
#define COPY_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void copy(FILE *in, FILE *out);
#endif
#include <stdlib.h>
#include <stdio.h>
#include "copy.h"
int main(int argc, char **argv) {
if (argc <=1) {
fputs("Not enough arguments.\nUsage: copy <source> <dest>\n", stderr);
exit(EXIT_FAILURE);
}
FILE *in = fopen(argv[1], "r");
if (!in) {
perror("Error opening input file");
exit(EXIT_FAILURE);
}
FILE *out;
if (argc == 2) {
out = stdout;
} else {
out = fopen(argv[2], "w");
if (!out) {
perror("Error opening output file");
exit(EXIT_FAILURE);
}
}
copy(in, out);
fclose(in);
fclose(out);
}
# $@ Le nom de la cible
# $< Le nom de la première dépendance
# $^ La liste des dépendances
# $? La liste des dépendances plus récentes que la cible
# $* Le nom du fichier sans suffixe
CC=gcc
CFLAGS=-Wall
LDFLAGS=
EXEC=copy
all: $(EXEC)
copy: copy.o exo3.o
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
%.o: %.c
$(CC) $(CFLAGS) -o $@ -c $< $(LDFLAGS)
clean:
rm -rf *.o *.ghc
mrproper: clean
rm -rf $(EXEC)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment