Вы находитесь на странице: 1из 24

Introduo Linguagem de Programao C

Laboratrio 04


Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



21

Seco 4


Pretende-se nesta seco introduzir os apontadores (tambm chamados de ponteiros). Os
apontadores so fundamentais na Linguagem C e a sua implementao um pouco diferente das
outras linguagens, pelo que ser a matria mais difcil de compreender. Os apontadores so
utilizados sobretudo em conjunto com vectores, estruturas e funes produzindo cdigo compacto e
eficiente.


Ponteiros ou apontadores


Um apontador uma varivel que contm o endereo de memria de outra varivel (diz-se
que aponta para ela). Declarao de apontadores:

tipo *nome_apontador;

Na programao com apontadores so utilizados dois operadores:

&nome_varivel que nos diz qual o endereo da varivel nome_varivel.
*nome_varivel que nos diz qual o valor que a varivel que est a ser apontada por
nome_varivel guarda.

Quando se declara um apontador ele no aponta para nada. H que colocar no apontador
um endereo vlido, 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 situaes onde pode ser necessrio declarar um apontador mas no o inicializar, neste
caso colocamo-lo a apontar para NULL.


Apontadores e funes


Na Linguagem C, existem umas algumas coisas que s se conseguem fazer utilizando
apontadores. Uma delas a modificao dos valores dos argumentos durante a execuo de uma
funo.
Imaginemos que queramos programar uma funo para trocar o valor de duas variveis.
Uma primeira aproximao seria:

#include <stdio.h>

void troca(int x, int y)
{
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 so de facto trocados? No!
Quando chamamos uma funo passando como argumentos variveis (neste caso
chamamos a funo troca() passando como argumentos as variveis a e b), procedemos cpia dos
valores que essas variveis possuem para as variveis que so os argumentos da funo (ie, a
varivel x vai guardar uma cpia do valor de a e a y do valor de b) e a funo vai executar as suas
operaes sobre as variveis dos argumentos (as variveis x e y) enquanto que as variveis que
foram passadas mantm os seus valores (ou seja, os valores das variveis x e y vo ser trocados
mas os das varveis a e b no).


Uma forma de alterar o valor de variveis dentro das funes utilizando variveis globais (o
que de evitar a todo o custo visto que torna os programas menos genricos e diminui a
possibilidade de reutilizao do cdigo por outro programa pois vai depender de variveis que podem
no existir. Outra passando como argumento da funo o endereo das variveis:

#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 programmos a funo troca() de forma a trabalharmos com os valores apontados por
x e y, e no criando cpias de valores que as variveis a e b guardam. Assim a funo troca() vai
realmente trocar os valores.





O porqu dos & no scanf()

Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



23
O scanf uma funo que pretende modificar o valor de variveis (as variveis passadas
como argumentos vo passar a ser conter os valores que o utilizador introduzir), e a nica forma de
o fazer passando o endereo dessas variveis.



Apontadores e vectores



Um vector um bloco de memria onde so armazenados em posies consecutivas
valores do mesmo tipo:

int a[10], x;
int *ptr_a;

ptr_a =&a[0]; /* ptr_a fica a apontar para a[0] - endereo inicial do vector a[] */

x =*ptr_a; /* x passa a ser igual a a[0] */

Para aceder-se posio i do vector possvel escrever:

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

vlido escrever:

ptr_a =a; em vez de ptr_a =&a[0];
(o endereo 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 construo equivalente
ptr_a[i] e *(ptr_a +i)

No entanto, existe uma diferena entre vectores e apontadores:

Um apontador uma varivel simples. Podem executar-se as seguintes instrues:
ptr_a =a e ptr_a++.
Um vector no uma varivel simples pelo que as seguintes construes so
invlidas: a =ptr_a e a++.
A passagem de um vector como argumento de uma funo faz-se sempre por
referncia, ou seja o que realmente passado funo o endereo da primeira
posio do vector, o que equivalente a passar um apontador para essa posio de
memria. Por exemplo, a chamada funo int strlen(char s[]); (funo que retorna
o tamanho da string s) pode ser feita de duas formas:

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

A declarao da funo strlen() tambm poderia ser feita como:

int strlen(char *s);



Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



24
Apontadores e estruturas



muito til e fcil utilizar estruturas e ponteiros em simultneo::

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 tambm 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 atravs 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
Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



25
Exerccios


4.1 Escreva uma funo (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 funo para calcular as razes de uma equao do
segundo grau utilizando a formula resolvente.

4.3 Programe as seguintes funes de manipulao de strings:

a) int strlen(char *s) - devolve o nmero 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 endereos, e que permita a procura por nome e
nmero.

Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



26

ANEXO A Solues dos Exerccios

Seco 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

Soluo:

#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
geomtrica e que escreve o seu permetro:

a) Sem utilizar vectores.

Soluo:

#include <stdio.h>

main()
{
int l1, l2, l3, l4, l5, l6;

printf("\nPerimetro de uma figura geomtrica 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.

Soluo:

#include <stdio.h>

main()
{
int l[6];

printf("\nPerimetro de uma figura geomtrica de seis lados\n\n");
printf("Introduza os valores dos lados: \n");
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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]);
}



Seco 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 J aneiro de 2004). Utilize no programa ambas as instrues if-else e
switch.

Soluo:

#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, J aneiro, 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, J unho, ano);
break;
}
case 7: {
Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



28
printf(\n%d de %s de %d, dia, J ulho, 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 converso de graus Celsius para
Fahrenheit. A tabela deve apresentar os graus Celsius de 0 a 40 de 2 em 2.

a) Recorrendo instruo for.

Soluo:

#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 instruo while.

Soluo:

#include <stdio.h>

main()
{
int i =0;

while (i <=40)
{
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 nmeros primos at n.

Soluo:

#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 sequncia de nmeros inteiros, e determine e imprima a
soma, a mdia, o menor e o maior dos nmeros:

a) Supondo que o comprimento da sequncia 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++)
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 sequncia indicado pelo valor 0 (que j no faz parte da sequncia).

Soluo:

#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 operao aritmtica, e, seguidamente, pede
os dois operandos sobre os quais quer realizar essa operao. O computador deve fazer a
operao apropriada e escrever o resultado no ecr. O programa quando detectar uma diviso
por zero dever escrever uma mensagem de erro.

Soluo:

#include <stdio.h>

Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 nmero de trs formas: uma usando a
instruo for, outra utilizando a instruo while e uma terceira com a instruo do ... while.

Soluo: (utilizando a instruo for)
#include <stdio.h>
main()
{
int i, n, fact =1;

printf("\nCalcula o factorial de n \n\n");
printf("\nIntroduza n: ");
scanf(" %d", &n);
Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



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



Seco 3

3.1 Escreva um programa que leia dois inteiros que representam o valor dos lados de um rectngulo
e que escreve a sua rea e permetro, recorrendo a funes.

Soluo:

#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 x
n
recorrendo a funes.

Soluo:

#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;

Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 funo int mdc(int x, int y) capaz de calcular o maior divisor comum
de dois inteiros, seguindo a definio acima.

Soluo:

#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
distncia entre eles.

Soluo:

Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 );
}


Seco 4

4.1 Escreva uma funo (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.

Soluo:

#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;
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 funo para calcular as razes de uma equao do
segundo grau utilizando a frmula resolvente.

Soluo:

#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 funes de strings:

a) int strlen(char *s) - devolve o nmero de caracteres existentes na string s.

Soluo:

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.

Soluo:
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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.

Soluo:

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;
}


Sistemas Operativos Ano lectivo de 2004/2005
Introduo Linguagem C Rossana Santos



37

ANEXO B Editor de texto: JOE

Overview
J OE is freeware. It is an ASCII text screen editor for UNIX and it makes full use
of the power and versatility of UNIX. J OE has the feel of most IBM PC text
editors: The key-sequences are reminiscent of WordStar and Turbo-C. J OE 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.

J OE's initialization file determines much of J OE's personality and the name of
the initialization file is simply the name of the editor executable followed by "rc".
J OE comes with four "rc" files in addition to the basic "joerc", which allow it to
emulate these editors
J PICO - An enhanced version of the Pine mailer system's PICO editor.
J STAR - A complete immitation of WordStar including many "J OE"
extensions.
RJ OE - A restricted version of J OE which allowed you to edit only the
files specified on the command line.
J MACS - An immitation of GNU-EMACS.


Starting J oe
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

Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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

Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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)


Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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

Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 \<, \>
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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
Sistemas Operativos Ano lectivo de 2004/2005
Introduo 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 youre 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.

J ustify

As you type, Picos 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, Picos word wrap feature automatically moves it to the beginning of the next line.

Вам также может понравиться