24
Introdução à Linguagem de Programação C Laboratório 04

Programação em C - Lab 04

Embed Size (px)

DESCRIPTION

Programação em C

Citation preview

Page 1: Programação em C - Lab 04

Introdução à Linguagem de Programação C

Laboratório 04

Page 2: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

21

Secção 4

Pretende-se nesta secção introduzir os apontadores (também chamados de ponteiros). Os

apontadores são fundamentais na Linguagem C e a sua implementação é um pouco diferente das outras linguagens, pelo que será a matéria mais difícil de compreender. Os apontadores são utilizados sobretudo em conjunto com vectores, estruturas e funções produzindo código compacto e eficiente.

Ponteiros ou apontadores

Um apontador é uma variável que contém o endereço de memória de outra variável (diz-se que aponta para ela). Declaração de apontadores:

tipo *nome_apontador; Na programação com apontadores são utilizados dois operadores:

&nome_variável que nos diz qual é o endereço da variável nome_variável. *nome_variável que nos diz qual o valor que a variável que está a ser apontada por

nome_variável guarda.

Quando se declara um apontador ele não aponta para nada. Há que colocar no apontador um endereço válido, antes de o poder utilizar (o melhor é iniciá-lo logo quando é criado).

Por exemplo:

float *ptr_pi, pi = 3.14; /* a variavel ptr_pi e um ponteiro para um real */ ptr_pi = π /* a variavel ptr_pi aponta para pi (foi inicializada) */ *ptr_pi = 3.1415; /* o valor apontado por ptr_pi vai passar a ser 3.1415 */ *ptr_pi = *ptr_pi + 0.00009265; /* podem realizar-se operacoes aritmeticas sobre

ponteiros */ Há situações onde pode ser necessário declarar um apontador mas não o inicializar, neste caso colocamo-lo a apontar para NULL.

Apontadores e funções

Na Linguagem C, existem umas algumas coisas que só se conseguem fazer utilizando apontadores. Uma delas é a modificação dos valores dos argumentos durante a execução de uma função.

Imaginemos que queríamos programar uma função para trocar o valor de duas variáveis. Uma primeira aproximação seria:

#include <stdio.h> void troca(int x, int y) {

Page 3: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

22

int aux;

aux = x; x = y; y = aux;

} main() {

int a = 2, b = 5;

troca(a, b); printf("%d %d", a, b );

}

Será que os valores são de facto trocados? Não! Quando chamamos uma função passando como argumentos variáveis (neste caso

chamamos a função troca() passando como argumentos as variáveis a e b), procedemos à cópia dos valores que essas variáveis possuem para as variáveis que são os argumentos da função (ie, a variável x vai guardar uma cópia do valor de a e a y do valor de b) e a função vai executar as suas operações sobre as variáveis dos argumentos (as variáveis x e y) enquanto que as variáveis que foram passadas mantém os seus valores (ou seja, os valores das variáveis x e y vão ser trocados mas os das varáveis a e b não).

Uma forma de alterar o valor de variáveis dentro das funções é utilizando variáveis globais (o

que é de evitar a todo o custo visto que torna os programas menos genéricos e diminui a possibilidade de reutilização do código por outro programa pois vai depender de variáveis que podem não existir. Outra é passando como argumento da função o endereço das variáveis:

#include <stdio.h>

void troca(int *x, int *y) {

int aux; aux = *x; *x = *y; *y = aux;

} main() {

int a = 2, b = 5; troca(&a, &b); printf("%d %d", a, b);

}

Agora programámos a função troca() de forma a trabalharmos com os valores apontados por x e y, e não criando cópias de valores que as variáveis a e b guardam. Assim a função troca() vai realmente trocar os valores.

O porquê dos & no scanf()

Page 4: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

23

O scanf é uma função que pretende modificar o valor de variáveis (as variáveis passadas como argumentos vão passar a ser conter os valores que o utilizador introduzir), e a única forma de o fazer é passando o endereço dessas variáveis. Apontadores e vectores

Um vector é um bloco de memória onde são armazenados em posições consecutivas valores do mesmo tipo:

int a[10], x; int *ptr_a; ptr_a = &a[0]; /* ptr_a fica a apontar para a[0] - endereço inicial do vector a[] */ x = *ptr_a; /* x passa a ser igual a a[0] */

Para aceder-se à posição i do vector é possível escrever:

*(ptr_a + i) que é equivalente a a[i]

É válido escrever:

ptr_a = a; em vez de ptr_a = &a[0]; (o endereço do primeiro elemento do vector é igual ao nome do vector)

Como a[i] é equivalente a *(ptr_a + i) temos que &(a[i]) é equivalente a ptr_a + i

Outra construção equivalente é

ptr_a[i] e *(ptr_a + i)

No entanto, existe uma diferença entre vectores e apontadores:

Um apontador é uma variável simples. Podem executar-se as seguintes instruções: ptr_a = a e ptr_a++ .

Um vector não é uma variável simples pelo que as seguintes construções são inválidas: a = ptr_a e a++ .

A passagem de um vector como argumento de uma função faz-se sempre por referência, ou seja o que realmente é passado à função é o endereço da primeira posição do vector, o que é equivalente a passar um apontador para essa posição de memória. Por exemplo, a chamada à função int strlen(char s[]); (função que retorna o tamanho da string s) pode ser feita de duas formas:

strlen(s) ou strlen(&s[0])

A declaração da função strlen() também poderia ser feita como:

int strlen(char *s);

Page 5: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

24

Apontadores e estruturas

É muito útil e fácil utilizar estruturas e ponteiros em simultâneo::

struct CD{ char titulo[50]; char grupo[30]; int ano; } cd; struct CD *ptr_cd; ptr_cd = &cd;

Para acedermos aos campos da estrutura utilizamos o operador: -> Por exemplo:

ptr_cd->titulo = “By The Way”; ptr_cd->grupo = “Red Hot Chili Peppers”; ptr_cd->ano = 2002;

Permite-nos também criar listas:

typedef struct { char titulo[50]; char grupo[30]; int ano; element *next; } element; element cd1, cd2; cd1.next = &cd2; cd2.next = NULL;

Os apontadores permitem ligar o elemento cd1 a cd2 através do seu membro next:

titulo grupo ano *next

Podemos percorrer a lista até que exista um elemento apontado igual a NULL.

titulo grupo ano *next

cd1 cd2

NULL

Page 6: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

25

Exercícios

4.1 Escreva uma função (e o respectivo programa de teste) que rode os seus 3 argumentos. Se estes se chamarem a, b e c, o valor de a vai para b, o valor de b vai para c e o valor de c vai para a. 4.2 Escreva um programa que utilize uma função para calcular as raízes de uma equação do segundo grau utilizando a formula resolvente. 4.3 Programe as seguintes funções de manipulação de strings:

a) int strlen(char *s) - devolve o número de caracteres existentes na string s. b) char *strcpy(char *dest, char *orig) - copia a string orig para a string dest. c) char *strcat(char *dest, char *orig) – coloca a string orig imediatamente a seguir ao

final da string dest. 4.4 Escreva um programe que simule uma lista de endereços, e que permita a procura por nome e número.

Page 7: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

26

ANEXO A – Soluções dos Exercícios

Secção 1

1.1 Escreva um programa que leia um valor real, representando graus Celsius e escreva o seu

equivalente em Fahrenheit na seguinte forma: 100.0 graus Celsius equivalem a 212.0 graus Fahrenheit

Solução: #include <stdio.h> main() { int celsius; printf(“\nConversao de graus Celsius para graus Fahrenheit\n\n“); printf(“Introduza os graus Celsius: “); scanf(“ %d”, &celsius); printf(“\n%d graus Celsius equivalem a %d graus Fahrenheit”, celsius, celsius + 112); }

1.2 Escreva um programa que leia 6 inteiros que representam o valor dos lados de uma figura

geométrica e que escreve o seu perímetro:

a) Sem utilizar vectores.

Solução:

#include <stdio.h> main() { int l1, l2, l3, l4, l5, l6; printf("\nPerimetro de uma figura geométrica de seis lados\n\n"); printf("Introduza os valores dos lados: \n"); scanf(" %d %d %d %d %d %d", &l1, &l2, &l3, &l4, &l5, &l6); printf("\nO perimetro da figura e: %d", l1 + l2+ l3 + l4 + l5 + l6); }

b) Utilizando vectores.

Solução: #include <stdio.h> main() { int l[6]; printf("\nPerimetro de uma figura geométrica de seis lados\n\n"); printf("Introduza os valores dos lados: \n");

Page 8: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

27

scanf(“ %d %d %d %d %d %d”, &l[0], &l[1], &l[2], &l[3], &l[4], &l[5]); printf("\nO perimetro da figura e: %d", l[0] + l[1] + l[2]+ l[3] + l[4] + l[5]); }

Secção 2

2.1. Escreva um programa que leia uma data, verifique se ela é valida e a escreva por extenso (por

exemplo: 01 01 2004 = 1 de Janeiro de 2004). Utilize no programa ambas as instruções if-else e switch.

Solução: #include <stdio.h> main() { int dia, mes, ano; printf(“\nOperacoes sobre datas\n\n”); printf(“Insira a data (formato: dia mes ano): ”); scanf(“ %d %d %d”, dia, mes, ano); if ((dia > 0) && (dia <= 31) && (mes > 0) && (mes <= 12)) {

switch(mes) { case 1: { printf(“\n%d de %s de %d”, dia, “Janeiro”, ano); break; } case 2: {

if (dia > 29) printf(“Data Invalida!”); else printf(“\n%d de %s de %d”, dia, “Fevereiro”, ano); break; } case 3: { printf(“\n%d de %s de %d”, dia, “Marco”, ano); break; } case 4: {

if (dia == 31) printf(“Data Invalida!”); else printf(“\n%d de %s de %d”, dia, “Abril”, ano); break; } case 5: { printf(“\n%d de %s de %d”, dia, “Maio”, ano); break; } case 6: {

if (dia == 31) printf(“Data Invalida!”); else printf(“\n%d de %s de %d”, dia, “Junho”, ano); break; } case 7: {

Page 9: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

28

printf(“\n%d de %s de %d”, dia, “Julho”, ano); break;

} case 8: { printf(“\n%d de %s de %d”, dia, “Agosto”, ano); break; } case 9: {

if (dia == 31) printf(“Data Invalida!”); else printf(“\n%d de %s de %d”, dia, “Setembro”, ano); break; } case 10: { printf(“\n%d de %s de %d”, dia, “Outubro”, ano); break; } case 11: {

if (dia == 31) printf(“Data Invalida!”); else printf(“\n%d de %s de %d”, dia, “Novembro”, ano); break; } case 12: { printf(“\n%d de %s de %d”, dia, “Dezembro”, ano); break; }

} } else printf(“Data Invalida!”); } 2.2. Escreva dois programas que escrevam no ecrã uma tabela de conversão de graus Celsius para

Fahrenheit. A tabela deve apresentar os graus Celsius de 0 a 40 de 2 em 2.

a) Recorrendo à instrução for. Solução: #include <stdio.h> main() { int i; printf(“\nConversao de graus Celsius para graus Fahrenheit\n\n“); for (i = 0; i <= 40; i += 2) printf(“\n%d graus Celsius equivalem a %d graus Fahrenheit”, i, i+112); } b) Recorrendo à instrução while. Solução: #include <stdio.h> main() { int i = 0; while (i <= 40) {

Page 10: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

29

printf(“\n%d graus Celsius equivalem a %d graus Fahrenheit”, i, i+112); i = i + 2; } }

2.3 Escreva um programa que leia um inteiro n e escreva todos os números primos até n.

Solução: #include<stdio.h> main() { int n, j, i, num; float resto; printf("\nMostra os numeros primos ate n \n\n"); printf("\nIntroduza n: "); scanf(" %d", &n); for (j = 1; j <= n; j++) { num =0; for(i = 1; i <= j; i++) { resto = j % i; if (resto == 0) num++; } if (num <= 2) printf("\n\t%d", j); } }

2.4 Escreva um programa que leia uma sequência de números inteiros, e determine e imprima a

soma, a média, o menor e o maior dos números:

a) Supondo que o comprimento da sequência é indicada previamente. #include<stdio.h> main() { int n, vec[100], i, soma, maior, menor; float media; printf("Qual o comprimento da sequencia? \n"); scanf(" %d",&n); for (i = 0; i < n; i++) { printf("Qual o numero?\n"); scanf(" %d",& vec[i]); } soma = 0; maior = vec[0]; menor = vec[0]; for (i = 0;i < n; i++)

Page 11: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

30

{ soma = soma + vec[i]; if(vec[i] > maior) maior = vec[i]; if(vec[i] < menor) menor = vec[i]; } media = soma / n; printf("A soma e: %d \n", soma); printf("A media e: %.2f \n", media); printf("O maior numero e: %d \n", maior); printf("O menor numero e: %d \n", menor); } b) Supondo que o fim da sequência é indicado pelo valor 0 (que já não faz parte da sequência). Solução: #include<stdio.h> main() { int n, vec[100], i = -1, soma, maior, menor; float media; n = -1; printf(“Insira numeros. 0 para terminar.\n”); do { i++; printf("Qual o numero?\n"); scanf(" %d", &vec[i]); n++; } while (vec[i] != 0); soma = 0; maior = vec[0]; menor = vec[0]; for (i = 0;i < n; i++) { soma = soma + vec[i]; if(vec[i] > maior) maior = vec[i]; if(vec[i] < menor) menor = vec[i]; } media = soma / n; printf("A soma e: %d \n", soma); printf("A media e: %.2f \n", media); printf("O maior numero e: %d \n", maior); printf("O menor numero e: %d \n", menor); }

2.5 Escreva um programa que pede para escolher uma operação aritmética, e, seguidamente, pede

os dois operandos sobre os quais quer realizar essa operação. O computador deve fazer a operação apropriada e escrever o resultado no ecrã. O programa quando detectar uma divisão por zero deverá escrever uma mensagem de erro.

Solução:

#include <stdio.h>

Page 12: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

31

main() { int num1, num2; char op; printf("Qual a operacao: \n"); scanf(" %c",&op); printf("Qual o primeiro valor: \n"); scanf(" %d",&num1); switch(op) { case ‘/’: { printf("Qual o segundo valor: \n"); scanf(" %d",&num2); if (num2 == 0) printf(“\nErro: divisao por zero\n”); else printf(“%d %c %d = %d”, num1, op, num2, num1 / num2); break; } case ‘*’: { printf("Qual o segundo valor: \n"); scanf(" %d",&num2); printf(“%d %c %d = %d”, num1, op, num2, num1 * num2); break; } case ‘+’: { printf("Qual o segundo valor: \n"); scanf(" %d",&num2); printf(“%d %c %d = %d”, num1, op, num2, num1 + num2); break; } case ‘-‘: { printf("Qual o segundo valor: \n"); scanf(" %d",&num2); printf(“%d %c %d = %d”, num1, op, num2, num1 - num2); break; } } }

2.6 Escreva um programa para calcular o factorial de um número de três formas: uma usando a

instrução for, outra utilizando a instrução while e uma terceira com a instrução do ... while.

Solução: (utilizando a instrução for)

#include <stdio.h>

main() { int i, n, fact = 1; printf("\nCalcula o factorial de n \n\n"); printf("\nIntroduza n: "); scanf(" %d", &n);

Page 13: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

32

for (i = 1; i <= n; i++) fact = fact * i; printf(“O factorial de %d e: %d”, n, fact); }

Secção 3

3.1 Escreva um programa que leia dois inteiros que representam o valor dos lados de um rectângulo

e que escreve a sua área e perímetro, recorrendo a funções.

Solução: #include <stdio.h> int perimetro(int comp, int larg) {

return 2 * comp + 2 * larg; } int area(int comp, int larg) {

return comp * larg; } main() { int comp, larg; printf(“\nCalculo do perimetro e da area de um rectangulo\n\n“); printf(“Introduza a largura do rectangulo: “); scanf(“ %d”, &larg); printf(“Introduza o comprimento do rectangulo: “); scanf(“ %d”, &comp); printf(“O seu perimetro e: %d e a sua area e: %d”, perimetro(comp,larg), area(comp, larg)); }

3.2 Escreva um programa que leia dois inteiros, x e n, e escreva xn recorrendo a funções.

Solução: #include <stdio.h> int potencia(int x, int n) { int aux = 1,i; for (i = 0; i < n; i++) aux = aux * x;

return aux; } main() { int x, n;

Page 14: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

33

printf(“\nCalculo da potencia n de um numero\n\n“); printf(“Introduza o numero: “); scanf(“ %d”, &x); printf(“Introduza a potencia: “); scanf(“ %d”, &n); printf(“O numero %d elevado a %d e: %d”, x, n, potencia(x, n)); }

3.3 O maior divisor comum (mdc) de dois inteiros x e y é o maior inteiro que divide tanto x como y

(com resto 0). Escreva uma função int mdc(int x, int y) capaz de calcular o maior divisor comum de dois inteiros, seguindo a definição acima.

Solução: #include<stdio.h> int mdc(int num1, int num2) { int i, aux; float resto_x, resto_y; if (num1<num2) aux = num1; else aux = num2; for (i = aux ; i > 0 ; i--) { resto_x = num1%i; resto_y = num2%i; if ((resto_x == 0) && (resto_y == 0)) { aux = i; i = 0; } } return aux; } main() { int num1, num2; printf("\nCalculo do maior divisor comum entre dois numeros\n\n"); printf("Introduza o primeiro numero: "); scanf(" %d", &num1); printf("Introduza o segundo numero: "); scanf(" %d", &num2); printf("O maior divisor comum de %d e %d e: %d ", num1, num2, mdc(num1, num2)); }

3.6 Escreva um programa que leia os valores das coordenadas de dois pontos e que calcule a

distância entre eles.

Solução:

Page 15: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

34

#include <stdio.h> #include <math.h> typedef struct { float x; float y; } ponto; float distancia( ponto a, ponto b ) { float dx, dy; dx = a.x - b.x; dy = a.y - b.y; return sqrt( dx*dx + dy*dy ); } main() { ponto p1, p2; float d; printf("\nCalculo da distancia entre dois pontos\n\n "); printf("Introduza as coordenadas x e y do ponto p1: "); scanf("%f %f", &p1.x, &p1.y ); printf("Introduza as coordenadas x e y do ponto p2: "); scanf("%f %f", &p2.x, &p2.y ); d = distancia( p1, p2 ); printf("A distancia entre os pontos e: %f\n", d ); }

Secção 4

4.1 Escreva uma função (e o respectivo programa de teste) que rode os seus 3 argumentos. Se

estes se chamarem a, b e c, o valor de a vai para b, o valor de b vai para c e o valor de c vai para a.

Solução:

#include <stdio.h> int roda(int *a, int *b, int *c) { int aux; aux = *a; *a = *b; *b = *c; *c = aux; } main() { int a, b, c;

Page 16: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

35

printf(“\Rodar tres numeros\n\n“); printf(“Introduza os valores de a, b, c: ”); scanf(“ %d %d %d”, &a, &b, &c); roda(&a, &b, &c); printf(“a = %d, b = %d, c = %d ”, a, b, c); }

4.2 Escreva um programa que utilize uma função para calcular as raízes de uma equação do

segundo grau utilizando a fórmula resolvente.

Solução: #include <stdio.h> #include <math.h> int raizes(double a, double b, double c, double *x1, double *x2) { double delta = b * b – 4.0 * a * c; if (delta >= 0.0) { *x1 = (-b + sqrt(delta)) / (2.0 * a); *x2 = (-b - sqrt(delta)) / (2.0 * a); return 1; } else return 0; } main() { double a, b, c, x1, x2; printf(“\nCalculo das raizes de uma equacao do segundo grau\n\n“); printf(“Introduza os valores de a, b, c na equacao: ”); scanf(“ %lf %lf %lf”, &a, &b, &c); if (raizes(a, b, c, &x1, &x2)) printf(“x1 = %4.2f \t x2 = %4.2f\n”, x1, x2); else printf(“Nao ha raizes”); }

4.3 Programe as seguintes funções de strings:

a) int strlen(char *s) - devolve o número de caracteres existentes na string s. Solução: int strlen(char *s) { int i = 0; while (s[i] != ‘\0’) i++; return i; } b) char *strcpy(char *dest, char *orig) - copia a string orig para a string dest.

Solução:

Page 17: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

36

char *strcpy(char *dest, char *orig) { int i = 0; for (i = 0; orig[i] != ‘\0’; i++) dest[i] = orig[i]; dest[i] = ‘\0’; return dest; }

c) char *strcat(char *dest, char *orig) – coloca a string orig imediatamente a seguir ao

final da string dest. Solução: char *strcat(char *dest, char *orig) { int i = 0; for (i = 0, len = strlen(dest); orig[i] != ‘\0’; i++, len++) dest[len] = orig[i]; dest[len] = ‘\0’; return dest; }

Page 18: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

37

ANEXO B – Editor de texto: JOE

Overview JOE is freeware. It is an ASCII text screen editor for UNIX and it makes full use

of the power and versatility of UNIX. JOE has the feel of most IBM PC text editors: The key-sequences are reminiscent of WordStar and Turbo-C. JOE has all of the features a UNIX user should expect: full use of termcap/terminfo, excellent screen update optimizations, and all of the UNIX-integration features of VI. JOE's initialization file determines much of JOE's personality and the name of the initialization file is simply the name of the editor executable followed by "rc". JOE comes with four "rc" files in addition to the basic "joerc", which allow it to emulate these editors

• JPICO - An enhanced version of the Pine mailer system's PICO editor. • JSTAR - A complete immitation of WordStar including many "JOE"

extensions. • RJOE - A restricted version of JOE which allowed you to edit only the

files specified on the command line. • JMACS - An immitation of GNU-EMACS.

Starting Joe To start joe, type joe at your prompt. To edit a file, type joe filename. The upper

left-hand side of the screen shows the name of the file you are editing and its status (whether the document is modified or not).

The upper right-hand side should display the help key. To get help, press the control key (CTRL) and k, then let go of both keys and press h. This key combination will be written as ^kh. To toggle the help screen off, repeat with ^kh.

Editing Working with Blocks of Text

You can manipulate large areas of text by defining the beginning and ending of a section and then performing operations on that block.

Mark Beginning Place the cursor where you wish the block to begin and type ^kb.

Mark End Place the cursor where you wish the block to end and type ^kk.

Now that the block is marked off, you can do the following:

Delete To delete the text block (or yank it), type ^ky.

Move To move the text of the block to another location (so that it is removed

Page 19: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

38

from its original location), position the cursor at the new location (where you would like to move the text) and type ^km.

Copy Text To copy the text of the block to another location (without deleting the original text), position the cursor at the new location (where you want to insert the copy) and type ^kc.

Write To write (save) the text of the block to a new file, type ^kw.

Quick Reference -- Movement ^b......................Scroll left

^f......................Scroll right ^x .....................Forward a word ^a .....................To left edge (of line) ^e..................... To right edge ^p..................... Line up ^n..................... Line down ^u..................... Screen up ^ku................... Top of Document ^v..................... Screen down ^kv ...................End of Document ^kl.................... Goto line #

-- Find & Replace ^k^f................... Find text

^kf ....................Find Next

-- Block ^kb.................. Mark beginning of block

^kk.................. Mark end of block ^kc ...................Copy block ^km .................Move block ^kw................. Save block ^ky ..................Erase block ^ko.................. Substitute block

-- Deleting ^d .....................Delete highlighted character

^w ....................Delete word: right ^o .....................Delete word: left ^j ......................Delete to the end of the line ^y..................... Delete whole line ^k- ...................Undo delete ^k+................... Redo delete

-- Miscellaneous ^t ......................Set format (margins, etc.)

^l ......................Redraw screen ^ka ....................Center words in line ^kj ....................Format line to margins

Page 20: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

39

^z ......................Suspend (to prompt) ^k, ....................Indent to left (pushes text to left) ^k. ....................Indent to right (pushes text to right)

-- Window Control ^ko ....................Split window

^kp ....................Switch to top window ^kn ....................Switch to bottom window ^kg ...................Grow size of current window ^kt .....................Shrink size of current window ^c ......................Close window

-- Macros ^k[ .....................Start recording a macro

^k] .....................Stop recording a macro ^k/ .....................Play a macro ^k= ....................Repeat a macro

-- File Functions ^kd .....................Save file

^kr .....................Insert a file ^ke .....................Open new file

-- Exit ^kx .....................Save and exit

^c .......................Exit (without save)

Page 21: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

40

ANEXO C – Editor de texto: vi

Vi Reference Card Modes Vi has two modes:

insertion mode, and command mode.

The editor begins in command mode, where cursor movement and text deletion and pasting occur. Insertion mode begins upon entering an insertion or change command. [ESC] returns the editor to command mode (where you can quit, for example by typing :q!). Most commands execute as soon as you type them except for \colon" commands which execute when you press the return key. Quitting

exit, saving changes :x quit (unless changes) :q quit (force, even if unsaved) :q!

Inserting text

insert before cursor, before line i , I append after cursor, after line a , A open new line after, line before o , O replace one char, many chars r , R

Motion

left, down, up, right h , j , k , l next word, blank delimited word w , W beginning of word, of blank delimited word b , B end of word, of blank delimited word e , E sentence back, forward ( , ) paragraph back, forward f { , } g beginning, end of line 0 , $ beginning, end of _le 1G , G line n nG or :n forward, back to char c fc , Fc top, middle, bottom of screen H , M , L

Deleting text Almost all deletion commands are performed by typing d followed by a motion. For example dw deletes a word. A few other deletions are:

character to right, left x , X to end of line D line dd line :d

Yanking text

Page 22: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

41

Like deletion, almost all yank commands are performed by typing y followed by a motion. For example y$ yanks to the end of line. Two other yank commands are:

line yy line :y

Changing text The change command is a deletion command that leaves the editor in insert mode. It is performed by typing c followed by a motion. For example cw changes a word. A few other change commands are:

to end of line C line cc

Putting text

put after position or after line p put before position or before line P

Bu_ers Named bu_ers may be speci_ed before any deletion, change, yank, or put command. The general pre_x has the form "c where c may be any lower case letter. For example, "adw deletes a word into bu_er a. It may thereafter be put back into the text with an appropriate put command, for example "ap. Markers Named markers may be set on any line of a _le. Any lowercase letter may be a marker name. Markers may also be used as the limits for ranges.

set marker c on this line mc goto marker c `c goto marker c _rst non-blank 'c

Search for Strings

search forward /string search backward ?string repeat search in same, reverse direction n , N

Replace The search and replace function is accomplished with the :s command. It is commonly used in combination with ranges or the :g command (below).

replace pattern with string :s/pattern /string /flags ags: all on each line, con_rm each g , c repeat last :s command &

Regular Expressions

any single character except newline . (dot) zero or more repeats * any character in set [...] any character not in set [^ ...] beginning, end of line ^ , $ beginning, end of word \< , \>

Page 23: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

42

grouping \ (… \ ) contents of n th grouping n \n

Counts Nearly every command may be preceded by a number that speci_es how many times it is to be performed. For example 5dw will delete 5 words and 3fe will move the cursor forward to the 3rd occurance of the letter e. Even insertions may be repeated conveniently with this method, say to insert the same line 100 times. Ranges Ranges may precede most \colon" commands and cause them to be executed on a line or lines. For example :3,7d would delete lines 3 _ 7. Ranges are commonly combined with the :s command to perform a replacement on several lines, as with :.,$s/pattern/string/g to make a replacement from the current line to the end of the _le.

lines n-m :n ,m current line :. last line :$ marker c :'c all lines :% all matching lines :g/pattern /

Files

write _le (current _le if no name given) :w file read _le after line :r file next _le :n previous _le :p edit _le :e file replace line with program output !!program

Other

toggle upper/lower case ~ join lines J repeat last text-changing command . undo last change, all changes on line u , U

Page 24: Programação em C - Lab 04

Sistemas Operativos Ano lectivo de 2004/2005

Introdução à Linguagem C Rossana Santos

43

ANEXO D – Editor de texto: pico

Pico: A Unix text editor Cursor movement To move the cursor, use the arrow keys or use Ctrl/f (forward), Ctrl/b (back), Ctrl/n (next line), Ctrl/p (previous line). Deleting text To delete the character to the left of the cursor, press Backspace, Delete, or Ctrl/h. To delete the character highlighted by the cursor, press Ctrl/d. To delete the current line, press Ctrl/k. Saving your work To save your edited file to disk, press Ctrl/o. Pico displays the current filename. (To save the file under a different name, delete the filename that Pico displays and type a new one.) Press Return. Redrawing the screen If your Pico screen becomes garbled, press Ctrl/L. Exiting Pico To exit Pico, press Ctrl/x. If you have made any changes since the last save, Pico asks whether to save them. Type y (yes) or n (no). If you type y, Pico displays the filename. (To save the edited file under a different name, delete the filename and type a new one.) Press Return. Searching for text Pico lets you search forward from the current cursor position for any text string you specify. Press Ctrl/w (for whereis) to invoke the search. Pico prompts you for a search term. To begin searching, type the text you’re looking for and press Return. Pico moves the cursor to the first instance of the text string you entered. You can find additional occurrences by pressing Ctrl/w again. Justify As you type, Pico’s word wrap automatically begins a new line when needed. However, when you edit existing text, you may create text lines that are either too short or too long. To rewrap or “justify” a paragraph, move the cursor to the paragraph and press Ctrl/j. To undo this action and restore the paragraph to its original condition, press Ctrl/u. Running Pico At your Unix shell prompt, type pico filename, replacing filename with the name of the file you want to create or edit. For example, to create a file and name it indiana.txt, type: pico indiana.txt Basic operations Pico displays a menu bar of commonly-used commands at the bottom of the screen. Pico accepts commands from your keyboard but not from your mouse. Inserting text To insert text into your Pico editing screen at the cursor, just begin typing. Pico inserts the text to the left of the cursor, moving any existing text along to the right. Each time the cursor reaches the end of a line, Pico’s word wrap feature automatically moves it to the beginning of the next line.