Browse Source

Fin TP2&3 partie 3

master
Elias Leinenweber 7 months ago
parent
commit
ca9dbf6bf5
  1. 56
      TP2and3/part3_IOs/sum_fscanf.c
  2. 26
      TP2and3/part3_IOs/sum_scanf.c

56
TP2and3/part3_IOs/sum_fscanf.c

@ -0,0 +1,56 @@
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
static void usage(void);
static void
usage(void)
{
extern char *__progname;
fprintf(stderr, "usage: %s filename\n", __progname);
exit(1);
}
int
main(int argc, char *argv[]) {
FILE *fp;
int i, integers[32], n = 0, res, sum = 0;
char *filename;
/* check that the user gave a correct number of parameters */
if (argc != 2)
usage();
filename = argv[1];
/* open file and retrieve integer values it contains */
if ((fp = fopen(filename, "r")) == NULL)
err(EXIT_FAILURE, "fopen");
/*
* check for the occurence of errors when using fopen and fscanf,
* display an error message and quit in case of errors.
*/
if ((res = fscanf(fp, "integer: %d", &integers[n++])) == 1)
while ((res = fscanf(fp, ", integer: %d", &integers[n])) == 1)
++n;
if (res == EOF)
err(EXIT_FAILURE, "fscanf");
for (i = 0; i < n; ++i)
sum += integers[i];
/* first variant: compute the sum of integer values and display it */
printf("Result: %d\n", sum);
/*
* second variant: compute the sum of integer values and print it in
* an output file
*/
fprintf(fopen("sum_result", "w+"), "%d", sum);
return EXIT_SUCCESS;
}

26
TP2and3/part3_IOs/sum_scanf.c

@ -0,0 +1,26 @@
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
int n1, n2;
/* display a message to indicate what users should write */
printf("Input an integer: ");
/* wait until users have provided you information */
/* check that information provided is an integer */
if (scanf("%d", &n1) < 1)
errx(EXIT_FAILURE, "Not integer");
/* repeat previous steps to get a second integer */
printf("Input another integer: ");
if (scanf("%d", &n2) < 1)
errx(EXIT_FAILURE, "Not integer");
/* compute the sum of integer values and display it */
printf("%d + %d = %d\n", n1, n2, n1 + n2);
return EXIT_SUCCESS;
}
Loading…
Cancel
Save