Linguagem C_Exercicios Propostos Solucao_10

Page 1


10.1

Linguagem C 25.ª Edição Atualizada e Aumentada FCA Editora (c) 2025

10

EXERCÍCIOS PROPOSTOS – SOLUÇÃO

1: #include <stdio.h>

2: #include <stdlib.h>

3:

4: #define MAX_STR 120 /* Dim. da maior string */ 5:

6: int main(int argc, char *argv[])

7: {

8: FILE *fp; 9: char s[MAX_STR+1]; /* Linha lida no ficheiro */ 10: int i=0; /* Contador das linhas */ 11:

12: if (argc==1)

13: { 14: fprintf(stderr, "Sintaxe: Line Ficheiro\n\n"); 15: exit(1); 16: } 17:

18: if ((fp=fopen(argv[1], "r"))==NULL)

19: { 20: fprintf(stderr, "Impossível abrir o ficheiro %s\n\n", argv[1]); 21: exit(1); 22: } 23:

24: while (fgets(s, MAX_STR+1, fp)!=NULL) 25: printf("%3d: %s", ++i, s); 26:

27: fclose(fp); 28: exit(0); 29: }

1: #include <stdio.h> 2: #include <string.h> 3: #include <stdlib.h>

4:

5: int main(int argc, char *argv[])

6: {

7: FILE *fp; 8: int so_total=0; /* Por Defeito, processa tudo */ 9: int n1, n2; /* Operandos */ 10: char op; /* Operador */ 11: long res, total=0L; /* Total acumulado */ 12:

13: if (argc==3) 14: so_total = (strcmp(argv[1], "-t")==0); /* ver se argv[1]=="-t" */ 15:

16: if (argc<2 || argc >3)

17: { 18: fprintf(stderr, "Sintaxe: proc [-t] ficheiro\n");

LINE.C

19: exit(1); 20: }

21:

22: if ((fp=fopen(argv[argc-1], "r"))==NULL)

23: { 24: fprintf(stderr, "Impossível abrir o aicheiro %s\n\n", argv[argc-1]); 25: exit(2);

26: }

27:

28: while (fscanf(fp, "%d %c%d", &n1, &op, &n2)==3) /* Leu as 3 vars */

29: { 30: switch(op)

31: {

32: case '+': res = (long) n1 + n2; break;

33: case '-': res = (long) n1 - n2; break;

34: case '*': res = (long) n1 * n2; break;

35: case '/': res = (long) n1 / n2; break;

36: }

37:

38: if (!so_total)

39: printf("%d %c %d = %ld\n", n1, op, n2, res);

40: total+=res;

41: }

42:

43: printf("%ld\n", total);

44: fclose(fp);

45: exit(0);

46: }

10.3

1: #include <stdio.h>

2: #include <string.h>

3: #include <stdlib.h>

4: #include <math.h>

5:

6: #define MAX_LIN 80

7: // instalação pode não incluir as macros min/max

8: #ifndef min

9: #define min(x, y) (((x)<(y))? (x) : (y))

10: #endif

11: #ifndef max

12: #define max(x, y) (((x)>(y))? (x) : (y))

13: #endif

14:

15: void Mostra(FILE*, char *, int pos1, int pos2); 16:

17: int main(int argc, char *argv[])

18: {

19: int i=1; // Para percorrer os Parâmetros 20: FILE *fin, *fout=stdout; // Ficheiros de Entrada e Saída 21: char linha[MAX_LIN+1]; // Variável com a linha do Fich 22:

23: int pos1=1, pos2=80; 24:

25: /* Testar a existência do Parâmetro do ficheiro de Output */

26: if (strncmp(argv[argc-1], "-o", 2)==0 || strncmp(argv[argc-1], "-O", 2)==0)

27: { if ((fout=fopen(argv[argc-1]+2, "wt"))==NULL)

28: { /* O ficheiro não foi criado */

29: fprintf(stderr, "Impossível criar o ficheiro [%s]\nOutput para o ecrã\n", argv[argc-1]+2);

30: fout = stdout;

31: }

32: argc--; /* Ultimo parâmetro já foi tratado */ 33: } 34:

PROC.C

35: /* Verificar se temos -pos1 */

36: if (argc>i && argv[i][0]=='-')

37: { pos1 = atoi(argv[i]+1);

38: /* Garantir que pos1 esta entre 1..MAX_LIN */

39: pos1 = min(max(pos1, 1), MAX_LIN);

40: i++;

41:

42: if (argc>i && argv[i][0]=='-')

43: { pos2 = atoi(argv[i]+1);

44: pos2 = max(1, min(pos2, MAX_LIN));

45: i++;

46: }

47: }

48:

49: for( ; i< argc; i++)

50: {

51: fin = fopen(argv[i], "rt");

52: if (fin==NULL)

53: continue; /* Passa ao próximo */

54:

55: fprintf(fout, "%s\n", argv[i]);

56: while (fgets(linha, MAX_LIN+1, fin)!=NULL)

57: { /* Retirar o '\n' */

58: if (linha[strlen(linha)-1]=='\n') linha[strlen(linha)-1]='\0';

59: Mostra(fout, linha, pos1, pos2);

60: }

61: fclose(fin);

62: }

63: return 0;

64: }

65:

66: /*

67: * Mostra os carateres existentes entre as posições pos1 .. pos2

68: * na string s

69: */

70: void Mostra(FILE *fp, char *s, int pos1, int pos2)

71: {

72: int len = strlen(s);

73: for (int i=pos1; i<=pos2 && i<=len ; i++)

74: fputc(s[i-1], fp); /* Strings em C começam no índice 0 */

75: fputc('\n', fp);

76: }}

1: #include <stdio.h>

2: #include <stdlib.h>

3: #include <string.h>

4:

5: #define MENOS '-'

6: #define MENOS_L "-l"

7: #define MAX_LIN 80

8:

9: void Erro_Fatal(int num_erro, char *string);

10:

11: int main(int argc, char *argv[])

12: {

13: int mostra_linhas = 0; /* Por defeito não mostra */ 14: int n_linha = 0; /* Nº da linha que estamos a processar */

15: FILE *fp=stdin;

16: char s[MAX_LIN+1];

17:

18: switch(argc)

19: { 20: case 1: break; 21:

10.5

22: case 2: if (strcmp(argv[1], MENOS_L)==0)

23: mostra_linhas=1;

24: else

25: if ((fp=fopen(argv[1], "r"))==NULL)

26: Erro_Fatal(2, argv[1]);

27: break;

28:

29: case 3: if (argv[1][0]!=MENOS)

30: Erro_Fatal(3, argv[1]); /* Flag inválida */

31: if (strcmp(argv[1], MENOS_L)!=0)

32: Erro_Fatal(3, argv[1]); /* Flag inválida */

33:

34: mostra_linhas=1;

35: if ((fp=fopen(argv[2], "r"))==NULL)

36: Erro_Fatal(2, argv[2]);

37:

38: break;

39: default: Erro_Fatal(1, "");

40: }

41:

42: while (fgets(s, MAX_LIN+1, fp)!=NULL)

43: {

44: if (s[strlen(s)-1]=='\n') // Se o último char for o \n

45: s[strlen(s)-1] = '\0'; // Tirar o \n da linha

46: if (mostra_linhas)

47: fprintf(stdout, "%d: ", ++n_linha);

48: fprintf(stdout, "%d\n", (int) strlen(s));

49: }

50:

51: fclose(fp);

52: return 0;

53: }

54:

55: void Erro_Fatal(int num_erro, char *string)

56: { 57: switch(num_erro)

58: {

59: case 1: /* Mostrar a Sintaxe */

60: fprintf(stderr, "Sintaxe: conta [-l] [Fich]\n\n"); 61: break;

62: case 2: /* Erro de Abertura no ficheiro */ 63: fprintf(stderr, "Imp. Abrir o ficheiro '%s'\n", string);

64: break;

65: case 3: /* Opção Inválida */

66: fprintf(stderr, "Opçao \"%s\" Inválida\n", string); 67: break;

68: }

69: exit(num_erro); 70: }

1: #include <stdio.h> 2: #include <stdlib.h> 3: 4: #define MAX_LIN 80 5:

6: int main(int argc, char *argv[])

7: { 8: int pos; 9: FILE *fin; 10: char linha[MAX_LIN+1]; /* Variável com a linha do Fich */ 11:

12: if (argc==1) return 1; 13: 14: if ((fin=fopen(argv[1], "rt"))==NULL)

CONTA.C

15: { 16: fprintf(stderr, "Impossível Abrir o Ficheiro %s\n", argv[1]);

17: return 2; 18: }

19:

20: while (fgets(linha, MAX_LIN+1, fin)!=NULL)

21: { 22: if (linha[0]=='$')

23: pos = atoi(linha+1);

24: if (pos>0 && pos<=argc-1)

25: puts(argv[pos+1]);

26: }

27:

28: fclose(fin);

29: return 0; 30: }

MY_SHOW/MY_SHOW.C

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
Linguagem C_Exercicios Propostos Solucao_10 by Grupo Lidel - Issuu