diff --git a/#28f.c b/#28f.c new file mode 100644 index 0000000..b82110e --- /dev/null +++ b/#28f.c @@ -0,0 +1,10 @@ +#inclu + +int main() { + + + + + +void imprimaMensagem(void) { /*inici a função define as funções que quer que a função realize) + /*bloco onde iram diff --git a/.capitulo_funcoes.c.swp b/.capitulo_funcoes.c.swp new file mode 100644 index 0000000..3460b1f Binary files /dev/null and b/.capitulo_funcoes.c.swp differ diff --git a/.cproject b/.cproject new file mode 100644 index 0000000..91a91d0 --- /dev/null +++ b/.cproject @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..3106291 --- /dev/null +++ b/.project @@ -0,0 +1,26 @@ + + + debug1 + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/1daula2 b/1daula2 new file mode 100644 index 0000000..669d35a Binary files /dev/null and b/1daula2 differ diff --git a/1daula2.c b/1daula2.c new file mode 100644 index 0000000..910ee7e --- /dev/null +++ b/1daula2.c @@ -0,0 +1,13 @@ +#include +main() { +int n1, n2, sol, res; +printf("Introduz o primeiro inteiro\n"); +scanf("%d", &n1); +printf("Introduz o segundo inteiro\n"); +scanf("%d",&n2); +sol=n1+n2; +printf("Introduz a tua resposta\n"); +scanf("%d",&res); +if (sol==res) printf("Parabens!!!\n"); +else printf("Enganaste-te! Tenta outra vez!\n"); +} diff --git a/2.1.c b/2.1.c new file mode 100644 index 0000000..022ec4b --- /dev/null +++ b/2.1.c @@ -0,0 +1,80 @@ +#include + +int main (void) +{ + int a, b, c; + int soma, menor, medio, maior; + + printf("Insira 3 números: "); + scanf("%d %d %d", &a, &b, &c); + + //a + if ( a*a + b*b == c*c || a*a + c*c == b*b || b*b + c*c == a*a ) + printf("Os números podem ser lados de um triângulo retângulo\n"); + else + printf("Os números não são lados de um triângulo retângulo\n"); + + //b + soma = a + b + c; + printf("A soma é %d\n", soma); + + //c + printf("O quadrado da soma é %d\n", soma*soma); + + //d + printf("A soma dos quadrados é %d\n", a*a+b*b+c*c); + + if (a >= b && a >= c) + { + maior = a; + if ( b >= c) + { + medio = b; + menor = c; + } + else + { + menor = c; + medio = b; + } + } + else if (b >= a && b >= c) + { + maior = b; + if ( a >= c) + { + medio = a; + menor = c; + } + else + { + menor = c; + medio = a; + } + } + else + { + maior = c; + if ( a >= b) + { + medio = a; + menor = b; + } + else + { + menor = b; + medio = a; + } + } + + //d + printf("O menor é %d\n", menor); + + //f + printf("O do meio é %d\n", medio); + + //g + printf("%d %d %d\n", menor, medio, maior); + + return 0; +} diff --git a/2.2.b.c b/2.2.b.c new file mode 100644 index 0000000..df60ae1 --- /dev/null +++ b/2.2.b.c @@ -0,0 +1,21 @@ +#include + +int main (void) +{ + int hor, min, seg, hor1, min1, seg1; + int h,m,s; + + printf("Insira o tempo 1 HH:mm:ss "); + scanf(" %d : %d : %d", &hor, &min, &seg); + + printf("Insira o tempo 2 HH:mm:ss "); + scanf(" %d : %d : %d", &hor1, &min1, &seg1); + + s = (seg - seg1 + 60) % 60; + m = ((min - min1 + 60) % 60 + (seg - seg1 - s) / 60 + 60) % 60; + h = (hor - hor1 + 24) % 24 + (min - min1 - m + (seg - seg1 - s) / 60) / 60; + + printf("A diferença %.2d:%.2d:%.2d\n", h, m ,s); + + return 0; +} diff --git a/2.2.c b/2.2.c new file mode 100644 index 0000000..2374fc4 --- /dev/null +++ b/2.2.c @@ -0,0 +1,26 @@ +#include + +int main (void) +{ + int seg, min, hor; + + printf("Insira um tempo em segundos: "); + scanf("%d", &seg); + + min = seg / 60; + hor = min / 60; + min %= 60; + seg %= 60; + + printf("%d:%d:%d\n", hor, min, seg); + + printf("Insira um tempo em HH:SS:MM "); + scanf(" %d : %d : %d", &hor, &min, &seg); + + seg += min * 60; + seg += hor * 3600; + + printf("Em segundos: %d\n", seg); + + return 0; +} diff --git a/2.3.c b/2.3.c new file mode 100644 index 0000000..fc44503 --- /dev/null +++ b/2.3.c @@ -0,0 +1,40 @@ +#include + +int main (void) +{ + int hor, min, hor1, min1; + int h,m; + float preco = 0.0; + + printf("Insira o tempo de entrada HH:mm "); + scanf(" %d : %d", &hor, &min); + + printf("Insira o tempo saída HH:mm "); + scanf(" %d : %d", &hor1, &min1); + + //com base em 2.2.b.c + m = (min1 - min + 60) % 60; + h = ((hor1 - hor + 24) % 24 + (min1 - min - m) / 60 + 60) % 60; + + h += (m + 59)/60; + + for (; h > 3 ; h--) preco += 1.0; + if (h == 3) + { + preco += 1.80; + h = 0; + } + else if (h == 2) + { + preco = 1.15; + h = 0; + } + else if (h == 1) + { + preco = 0.5; + h = 0; + } + + printf("A pagar do estacionamento: %2.2f€\n", preco); + return 0; +} diff --git a/2.4.c b/2.4.c new file mode 100644 index 0000000..74f7a67 --- /dev/null +++ b/2.4.c @@ -0,0 +1,24 @@ +#include + +int main (void) +{ + float p, d; + + printf("Insira o valor do preço do artigo: "); + scanf("%f", &p); + + if (p > 50.0) + d = 0.4; + else if (p > 25 && p <= 50) + d = 0.2; + else if (p > 10 && p <= 25) + d = 0.1; + else + d = 0.05; + + p *= (1.0 - d); + + printf("O preço de desconto é: %2.2f\n", p); + return 0; +} + diff --git a/2.5.c b/2.5.c new file mode 100644 index 0000000..fda0cdf Binary files /dev/null and b/2.5.c differ diff --git "a/2\302\272aula17" "b/2\302\272aula17" new file mode 100644 index 0000000..b212a29 Binary files /dev/null and "b/2\302\272aula17" differ diff --git "a/2\302\272aula17.c" "b/2\302\272aula17.c" new file mode 100644 index 0000000..84f2c30 --- /dev/null +++ "b/2\302\272aula17.c" @@ -0,0 +1,17 @@ +#include +int main(void) + { + int n,m; + printf("escreve o valor do primeiro e segundo valores, respectivamente\n"); + scanf("%d%d",&n,&m); + if (m==0) + puts("Divisão por 0 não terá êxito"); + else + { + if (n%m==0) + printf("%d divide %d, ou %d é divisível por %d",m,n,n,m); + else + printf("A propriedade não se verifica"); + } + return 0; + } diff --git "a/3\302\272aula17" "b/3\302\272aula17" new file mode 100644 index 0000000..4f2291e Binary files /dev/null and "b/3\302\272aula17" differ diff --git "a/3\302\272aula17.c" "b/3\302\272aula17.c" new file mode 100644 index 0000000..8d5b036 --- /dev/null +++ "b/3\302\272aula17.c" @@ -0,0 +1,30 @@ +#include +int main(void) + { + int n; + printf("escreve a um número a inverter:\t"); + scanf("%d",&n); + puts("\vO número invertido será:"); + /*if (n<10 && n>0) + printf("%d",n);*/ + while(n>0)//ao invês de 10 + { + printf("%d",n%10);//paratirar uma cifra divido por dez + n/=10;//ele faz cifra=n%10 e imprime + } + + while(n<0)//for (n<0;n=0;n/10) + { + //se quiser por dentro do while ->if (n<0) + n*=-1;printf("-"); + + while(n>0)//ao invês de 10 + { + printf("%d",n%10);//paratirar uma cifra divido por dez + n/=10;//ele faz cifra=n%10 e imprime + } + } + puts (""); + return 0; + } + diff --git "a/3\302\272aula17.o" "b/3\302\272aula17.o" new file mode 100644 index 0000000..2857586 Binary files /dev/null and "b/3\302\272aula17.o" differ diff --git a/8 - Ponteiros, ponteiros e vetores e alocacao dinamica de memoria.pdf b/8 - Ponteiros, ponteiros e vetores e alocacao dinamica de memoria.pdf new file mode 100644 index 0000000..67912db Binary files /dev/null and b/8 - Ponteiros, ponteiros e vetores e alocacao dinamica de memoria.pdf differ diff --git a/ASCII b/ASCII new file mode 100644 index 0000000..2a6b86e Binary files /dev/null and b/ASCII differ diff --git a/ASCII.c b/ASCII.c new file mode 100644 index 0000000..5b2acb4 --- /dev/null +++ b/ASCII.c @@ -0,0 +1,11 @@ +#include + + + int main() { + + int i; + for ( i = 30; i < 129; i++ ) { + printf( "%c[%d]\n", i , i ); + } +return 0; +} diff --git a/Aula28.c b/Aula28.c new file mode 100644 index 0000000..410dc5e --- /dev/null +++ b/Aula28.c @@ -0,0 +1,7 @@ +#include +int main () +{ + void impirmaMensagem(void);//é necessário usar a declaração caso ela esteja por baixo da main para ouder usa-la posteriormente . Motivos de organização é sempre melhor declarar as funções(seja muitas :)) + imprimaMensagem(); + return =0; + } diff --git a/MUTEX/15threads_semaphores_simple.c b/MUTEX/15threads_semaphores_simple.c new file mode 100644 index 0000000..de2cc87 --- /dev/null +++ b/MUTEX/15threads_semaphores_simple.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include +#include + +void *myfunc1(void *myvar); +void *myfunc2(void *myvar); + +char buf[24]; + +sem_t mutex; + +int main(int argc, char *argv[]) { + + pthread_t thread1, thread2; + + char *msg1 = "Thread 1"; + char *msg2 = "Thread 2"; + + sem_init(&mutex, 0, 1); + + pthread_create(&thread1, NULL, myfunc1, (void *) msg1); + pthread_create(&thread2, NULL, myfunc2, (void *) msg2); + + pthread_join(thread1, NULL); + pthread_join(thread2, NULL); + + sem_destroy(&mutex); + + return 0; +} + + +void *myfunc1(void *ptr) { + char *msg = (char *) ptr; + printf("%s\n", msg); + + sem_wait(&mutex); + sprintf(buf, "%s", "Hello there!"); + sem_post(&mutex); + + pthread_exit(0); +} + + +void *myfunc2(void *ptr) { + char *msg = (char *) ptr; + printf("%s\n", msg); + + sem_wait(&mutex); + printf("%s\n", buf); + sem_post(&mutex); + + + pthread_exit(0); +} \ No newline at end of file diff --git a/PIPEs/folha5.pdf b/PIPEs/folha5.pdf new file mode 100644 index 0000000..b2ed05c Binary files /dev/null and b/PIPEs/folha5.pdf differ diff --git a/PIPEs/p1a b/PIPEs/p1a new file mode 100644 index 0000000..ddb67bb Binary files /dev/null and b/PIPEs/p1a differ diff --git a/PIPEs/p1a.c b/PIPEs/p1a.c new file mode 100644 index 0000000..163acc7 --- /dev/null +++ b/PIPEs/p1a.c @@ -0,0 +1,37 @@ +#include +#include + +#define READ 0 +#define WRITE 1 + +int main() { + int fd[2]; + pid_t pid; + + pipe(fd); + pid = fork(); + if (pid >0) { //pai + int a, b; + + printf("PARENT:\n"); + printf("x y ? "); scanf("%d %d", &a, &b); + close(fd[READ]); + write(fd[WRITE], &a, sizeof(int)); + write(fd[WRITE], &b, sizeof(int)); + close(fd[WRITE]); + } + else { //filho + int x, y; + + close(fd[WRITE]); + read(fd[READ], &x, sizeof(int)); + read(fd[READ], &y, sizeof(int)); + printf("SON:\n"); + printf("x + y = %d\n", x+y); + printf("x + y = %d\n", x-y); + printf("x + y = %d\n", x*y); + printf("x + y = %d\n", x/y); + close(fd[READ]); + } + return 0; +} diff --git a/PIPEs/p1b b/PIPEs/p1b new file mode 100644 index 0000000..9dd8964 Binary files /dev/null and b/PIPEs/p1b differ diff --git a/PIPEs/p1b.c b/PIPEs/p1b.c new file mode 100644 index 0000000..f03d7d2 --- /dev/null +++ b/PIPEs/p1b.c @@ -0,0 +1,36 @@ +#include +#include + +#define READ 0 +#define WRITE 1 + +int main() { + int fd[2]; + pid_t pid; + + pipe(fd); + pid = fork(); + if (pid >0) { //pai + struct { + int a, b; + } sn; + + printf("PARENT:\n"); + printf("x y ? "); scanf("%d %d", &(sn.a), &(sn.b)); + close(fd[READ]); + write(fd[WRITE], &sn, sizeof(sn)); + close(fd[WRITE]); + } + else { //filho + struct { + int x, y; + } vals; + + close(fd[WRITE]); + read(fd[READ], &vals, sizeof(vals)); + printf("SON:\n"); + printf("x + y = %d\n", vals.x+vals.y); + close(fd[READ]); + } + return 0; +} diff --git a/PIPEs/teoric b/PIPEs/teoric new file mode 100644 index 0000000..6b0211f Binary files /dev/null and b/PIPEs/teoric differ diff --git a/PIPEs/teoric.c b/PIPEs/teoric.c new file mode 100644 index 0000000..58e270a --- /dev/null +++ b/PIPEs/teoric.c @@ -0,0 +1,32 @@ +//Pipes e FIFO's 3 Exemplo Pipe entre pai e filho: +#include +#include +#include +#include +#define MAXLINE 128 +int main (void) +{ + int n, fd[2]; + pid_t pid; + char line[MAXLINE]; + pipe (fd); + pid = fork (); + if (pid > 0) + { +/* pai */ + close (fd[0]); +/* fecha lado receptor do pipe */ + write (fd[1], "hello world \n", 12); + close (fd[1]); + } + else + { +/* filho */ + close (fd[1]); +/* fecha lado emissor do pipe */ + n = read (fd[0], line, MAXLINE); + write (STDOUT_FILENO, line, n); + close (fd[0]); + } + return 0; +} diff --git a/PIPEs/teoric.c~ b/PIPEs/teoric.c~ new file mode 100644 index 0000000..d74384e --- /dev/null +++ b/PIPEs/teoric.c~ @@ -0,0 +1,30 @@ +//Pipes e FIFO's 3 Exemplo Pipe entre pai e filho: +#include +#include +#include +#include +#define MAXLINE 128 +int main(void) +{ +int n, fd[2]; +pid_tpid; +char line[MAXLINE]; +pipe(fd); +pid = fork( ); +if (pid > 0) { +/* pai */ +close(fd[0]); +/* fecha lado receptor do pipe */ +write(fd[1], "hello world \n", 12); +close(fd[1]); +} +else { +/* filho */ +close(fd[1]); +/* fecha lado emissor do pipe */ +n = read(fd[0], line, MAXLINE); +write(STDOUT_FILENO, line, n); +close(fd[0]); +} +return 0; +} diff --git a/Proj1/Makefile b/Proj1/Makefile new file mode 100644 index 0000000..609b440 --- /dev/null +++ b/Proj1/Makefile @@ -0,0 +1,18 @@ +CC = gcc + +CFLAGS = -Wall + +TARGET = rmdup + +DEPS = rmdup.h lstdir.h + +all: rmdup lstdir + +bin: + mkdir bin + +rmdup: rmdup.c + $(CC) $(CFLAGS) -o bin/rmdup rmdup.c + +lstdir: lstdir.c + $(CC) $(CFLAGS) -o bin/lstdir lstdir.c diff --git a/Proj1/lstdir.c b/Proj1/lstdir.c new file mode 100644 index 0000000..b497e7c --- /dev/null +++ b/Proj1/lstdir.c @@ -0,0 +1,81 @@ +#include "lstdir.h" + +int lstdir(const char * filepath) +{ + DIR *dirp; //directory file + struct dirent *direntp; //dirent struct + struct stat stat_buf; //stat struct + + + if((dirp = opendir(filepath)) == NULL) + { + perror(filepath); + exit(3); + } + + while((direntp = readdir(dirp)) != NULL) + { + char filestr[strlen(filepath)+strlen(direntp->d_name)]; //file path + sprintf(filestr,"%s/%s",filepath,direntp->d_name); + + if(lstat(filestr, &stat_buf)==-1) + { + perror("lstat ERROR"); + exit(3); + } + + if(strcmp(direntp->d_name, ".") !=0 && strcmp(direntp->d_name, "..") != 0) + { + if (S_ISREG(stat_buf.st_mode)) + { + if(access(filestr, W_OK) == 0 && access(filestr, R_OK) == 0) + { + printf("%-35s - ", direntp->d_name); //name + printf("%li - ", stat_buf.st_mtime); //last modified time + printf("%6li - ", stat_buf.st_size); //size + printf("%04o - ", stat_buf.st_mode & 0777); //permisiion + printf("%li - ", stat_buf.st_ino); //inode + printf("%s - \n",filestr); //path + } + + } + else if(S_ISDIR(stat_buf.st_mode)) + { + if(access(filestr, W_OK) == 0 && access(filestr, R_OK) == 0) + { + pid_t pid = fork(); + + if(pid == 0) + { + lstdir(filestr); + exit(0); + } + else if(pid > 0) + { + waitpid(pid, NULL,0); + } + } + + } + } + } + + //CLOSING AND EXITING + closedir(dirp); + exit(0); +} + +int main(int argc, char* argv[]) +{ + //ARGUMENTS TEST + if(argc != 2) + { + printf("Usage: %s \n", argv[0]); + exit(1); + } + + if(lstdir(argv[1]) > 0) + exit(2); + + exit(0); +} diff --git a/Proj1/lstdir.h b/Proj1/lstdir.h new file mode 100644 index 0000000..b497e7c --- /dev/null +++ b/Proj1/lstdir.h @@ -0,0 +1,81 @@ +#include "lstdir.h" + +int lstdir(const char * filepath) +{ + DIR *dirp; //directory file + struct dirent *direntp; //dirent struct + struct stat stat_buf; //stat struct + + + if((dirp = opendir(filepath)) == NULL) + { + perror(filepath); + exit(3); + } + + while((direntp = readdir(dirp)) != NULL) + { + char filestr[strlen(filepath)+strlen(direntp->d_name)]; //file path + sprintf(filestr,"%s/%s",filepath,direntp->d_name); + + if(lstat(filestr, &stat_buf)==-1) + { + perror("lstat ERROR"); + exit(3); + } + + if(strcmp(direntp->d_name, ".") !=0 && strcmp(direntp->d_name, "..") != 0) + { + if (S_ISREG(stat_buf.st_mode)) + { + if(access(filestr, W_OK) == 0 && access(filestr, R_OK) == 0) + { + printf("%-35s - ", direntp->d_name); //name + printf("%li - ", stat_buf.st_mtime); //last modified time + printf("%6li - ", stat_buf.st_size); //size + printf("%04o - ", stat_buf.st_mode & 0777); //permisiion + printf("%li - ", stat_buf.st_ino); //inode + printf("%s - \n",filestr); //path + } + + } + else if(S_ISDIR(stat_buf.st_mode)) + { + if(access(filestr, W_OK) == 0 && access(filestr, R_OK) == 0) + { + pid_t pid = fork(); + + if(pid == 0) + { + lstdir(filestr); + exit(0); + } + else if(pid > 0) + { + waitpid(pid, NULL,0); + } + } + + } + } + } + + //CLOSING AND EXITING + closedir(dirp); + exit(0); +} + +int main(int argc, char* argv[]) +{ + //ARGUMENTS TEST + if(argc != 2) + { + printf("Usage: %s \n", argv[0]); + exit(1); + } + + if(lstdir(argv[1]) > 0) + exit(2); + + exit(0); +} diff --git a/Proj1/rmdup.c b/Proj1/rmdup.c new file mode 100644 index 0000000..84d366c --- /dev/null +++ b/Proj1/rmdup.c @@ -0,0 +1,317 @@ +#include "rmdup.h" + +int list_dir(const char * path, int file) +{ + int stdout_fileno = dup(STDOUT_FILENO); + dup2(file, STDOUT_FILENO); + + //calling lstdir + //child will execute and father waits + pid_t pid = fork(); + + if(pid == 0) + { + if(execl("./lstdir","./lstdir",path,NULL) < 0) + exit(3); + fflush(stdout); + exit(0); + } + else if(pid > 0) + { + waitpid(pid, NULL, 0); + dup2(stdout_fileno, STDOUT_FILENO); + } + else + { + dup2(stdout_fileno, STDOUT_FILENO); + perror(path); + exit(-1); + } + + dup2(stdout_fileno, STDOUT_FILENO); + return 0; +} + +int sort_file(const char * filepathaux, int file) +{ + int stdout_fileno = dup(STDOUT_FILENO); + dup2(file, STDOUT_FILENO); + + //sorting filepathaux to file + pid_t pid = fork(); + + if(pid == 0) + { + execlp("sort", "sort", filepathaux, NULL); + fflush(stdout); + exit(0); + } + else if(pid > 0) + { + waitpid(pid, NULL, 0); + dup2(stdout_fileno, STDOUT_FILENO); + } + else + { + dup2(stdout_fileno, STDOUT_FILENO); + perror(filepathaux); + exit(-1); + } + dup2(stdout_fileno, STDOUT_FILENO); + return 0; +} + +void str_split(struct File* stru, char * str) +{ + + char *token; + char *search = " - "; + + //name + token = strtok(str, search); + strcpy(stru->name, token); + + //time + token = strtok(NULL, search); + stru->time = atoi(token); + + //size + token = strtok(NULL, search); + stru->size = atoi(token); + + //permission + token = strtok(NULL, search); + stru->perm = atoi(token); + + //inode + token = strtok(NULL, search); + stru->inode = atoi(token); + + //path + token = strtok(NULL, search); + strcpy(stru->path, token); +} + +int test_link(struct File* stru1, struct File* stru2) +{ + + if(strcmp(stru1->path, stru2->path) == 0) + { + return 0; + } + + struct stat stat_buf1; + struct stat stat_buf2; + lstat(stru1->path, &stat_buf1); + lstat(stru2->path, &stat_buf2); + + if(stat_buf1.st_ino == stat_buf2.st_ino) + return 0; + + //equal files + if((strcmp(stru1->name, stru2->name) == 0) && (stru1->size == stru2->size) && (stru1->perm == stru2->perm)) + { + if(stru1->time < stru2->time) + { + if(remove(stru1->path) == -1) + perror(stru1->path); + link(stru2->path, stru1->path); + printf("Deleted %s and created hardlink to %s\n", stru1->path, stru2->path); + return 1; + } + + else if(stru1->time > stru2->time) + { + + if(remove(stru2->path) == -1) + perror(stru2->path); + link(stru1->path, stru2->path); + printf("Deleted %s and created hardlink to %s\n", stru2->path, stru1->path); + return 1; + } + } + return 0; + + +} + +int search_lines(int hlinks,const char * path) +{ + int retval = 0; + FILE *fr1; + FILE *fr2; + char line1[MAX_BUFF]; + char line2[MAX_BUFF]; + int stdout_fileno = dup(STDOUT_FILENO); + dup2(hlinks, STDOUT_FILENO); + + struct File * Test1 = malloc (sizeof(*Test1)); //struct for file + struct File * Test2 = malloc (sizeof(*Test2)); //struct for file + + + fr1 = fopen (path, "rt"); + + while(fgets(line1, MAX_BUFF, fr1) != NULL) + { + str_split(Test1, line1); + + fr2 = fopen (path, "rt"); + while(fgets(line2, MAX_BUFF, fr2) != NULL) + { + str_split(Test2, line2); + if(test_link(Test1, Test2) == 1) + { + retval = 1; + } + } + } + fflush(stdout); + fclose(fr1); + fclose(fr2); + free(Test1); + free(Test2); + dup2(stdout_fileno, STDOUT_FILENO); + return retval; +} + +int main(int argc, char* argv[]) +{ + + //local variables + char* filepath = "/tmp/files.txt"; //files.txt path dir + char* filepathaux = "/tmp/filesaux.txt"; //filesaux.txt path dir + char* hlink = "/hlinks.txt"; //hardlinks.txt filespath + int file; //files.txt descriptor + int fileaux; //filesaux.txt descriptor + int filelink; //hlinks.txt descriptor + struct stat mypath; //struct to test path + + //creating path for linkspath + char linkspath[strlen(argv[1]) + strlen(hlink) + 1]; + strcpy(linkspath, argv[1]); + strcat(linkspath, hlink); + + //argument test + if(argc != 2) + { + printf("Usage: %s \n", argv[0]); + exit(1); + } + + if(linkspath[0] != '/') + { + printf("Invalid link, must start with semicolon \n"); + exit(1); + } + + if (stat(argv[1], &mypath) < 0) + { + printf("Invalid path, unable to find path\n"); + exit(1); + } + else if (!S_ISDIR(mypath.st_mode)) + { + printf("Invalid path\n"); + exit(1); + } + + //formating existing files + remove(linkspath); + remove(filepathaux); + remove(filepath); + + //creating filesaux in tmp area + if((fileaux = open(filepathaux, O_RDWR | O_APPEND | O_CREAT, 0600)) < 0) + { + perror(filepathaux); + exit(2); + } + + //creating files.txt tmp area + if((file = open(filepath, O_RDWR | O_APPEND | O_CREAT, 0600)) < 0) + { + perror(filepath); + exit(2); + } + + //creating hlinks.txt in tmp area + if((filelink = open(linkspath, O_RDWR | O_APPEND | O_CREAT, 0600)) < 0) + { + perror(linkspath); + exit(2); + } + + + //saving stdout_fileno descryptor and writing to file + if(list_dir(argv[1], fileaux) != 0) + { + printf("List Directory error \n"); + exit(3); + } + printf("Listed Directory\n"); + + //sorting from filesaux.txt to files.txt + if(sort_file(filepathaux, file) != 0) + { + printf("Sort File error \n"); + exit(4); + } + printf("Sorted File\n"); + + //creating hardlinks + int ret = search_lines(filelink, filepath); + if(ret < 0) + { + printf("Error Searching Lines\n"); + exit(5); + } + else if(ret == 1) + { + printf("Hardlinks Created\n"); + } + else if(ret == 0) + { + printf("No Hardlinks found\n"); + } + + + remove(filepathaux); + if((fileaux = open(filepathaux, O_RDWR | O_APPEND | O_CREAT, 0600)) < 0) + { + perror(argv[1]); + exit(2); + } + + //saving stdout_fileno descryptor and writing to file + if(list_dir(argv[1], fileaux) != 0) + { + printf("List Directory error \n"); + exit(3); + } + printf("Listed Directory\n"); + + //temporary change to give enter in files.txt + int stdout_fileno = dup(STDOUT_FILENO); + dup2(file, STDOUT_FILENO); + printf("\n.:New Listed\n"); + fflush(stdout); + dup2(stdout_fileno, STDOUT_FILENO); + + + //sorting from filesaux.txt to files.txt + if(sort_file(filepathaux, file) != 0) + { + printf("Sort File error \n"); + exit(4); + } + printf("Sorted File"); + + //Removing filepath txt file + remove(filepathaux); + + //Closing and exiting + close(file); + close(fileaux); + close(filelink); + exit(0); +} diff --git a/Proj1/rmdup.h b/Proj1/rmdup.h new file mode 100644 index 0000000..b35d72c --- /dev/null +++ b/Proj1/rmdup.h @@ -0,0 +1,71 @@ +#ifndef RMDUP_H +#define RMDUP_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_BUFF 1024 + +struct File +{ + char name[MAX_BUFF]; + int size; + int inode; + int perm; + int time; + char path[MAX_BUFF]; +}; + +/** +* list_dir will change STDOUT_FILENO to @param file in order to use +* printf to write in the file. +* It uses Multi-processing and calls ./lstdir with @param path as parameter +* Restores STDOUT_FILENO to terminal. +*/ + +int list_dir(const char * path, int file); + +/** +* sort_file will change STDOUT_FILENO to @param file in order to use +* printf to write in the file. +* It calls sort program with @param path filepathaux as a parameter. +* Will sort filepathaux and writes it to file +* Restores STDOUT_FILENO to terminal. +*/ + +int sort_file(const char * filepathaux, int file); + +/** +* str_split splits the line @param str in various elements and saves +* each accordingly to the @param stru struct elements +*/ + +void str_split(struct File* stru, char * str); + +/** +* test_link will test the information passed through @param stru1 struct +* and @param stru2 struct and create the links acordingly +*/ + +int test_link(struct File* stru1, struct File* stru2); + +/** +* searh_lines will change STDOUT_FILENO to @param hlinks in order to +* write every hardlink created to that file using printf +* It will read each line from file @param path and compare all possiblities +* using test_link. +* Uses str_split to split all possibile comparisons into file. +*/ + +int search_lines(int hlinks,const char * path); + +#endif diff --git a/Proj1/untitled b/Proj1/untitled new file mode 100644 index 0000000..b497e7c --- /dev/null +++ b/Proj1/untitled @@ -0,0 +1,81 @@ +#include "lstdir.h" + +int lstdir(const char * filepath) +{ + DIR *dirp; //directory file + struct dirent *direntp; //dirent struct + struct stat stat_buf; //stat struct + + + if((dirp = opendir(filepath)) == NULL) + { + perror(filepath); + exit(3); + } + + while((direntp = readdir(dirp)) != NULL) + { + char filestr[strlen(filepath)+strlen(direntp->d_name)]; //file path + sprintf(filestr,"%s/%s",filepath,direntp->d_name); + + if(lstat(filestr, &stat_buf)==-1) + { + perror("lstat ERROR"); + exit(3); + } + + if(strcmp(direntp->d_name, ".") !=0 && strcmp(direntp->d_name, "..") != 0) + { + if (S_ISREG(stat_buf.st_mode)) + { + if(access(filestr, W_OK) == 0 && access(filestr, R_OK) == 0) + { + printf("%-35s - ", direntp->d_name); //name + printf("%li - ", stat_buf.st_mtime); //last modified time + printf("%6li - ", stat_buf.st_size); //size + printf("%04o - ", stat_buf.st_mode & 0777); //permisiion + printf("%li - ", stat_buf.st_ino); //inode + printf("%s - \n",filestr); //path + } + + } + else if(S_ISDIR(stat_buf.st_mode)) + { + if(access(filestr, W_OK) == 0 && access(filestr, R_OK) == 0) + { + pid_t pid = fork(); + + if(pid == 0) + { + lstdir(filestr); + exit(0); + } + else if(pid > 0) + { + waitpid(pid, NULL,0); + } + } + + } + } + } + + //CLOSING AND EXITING + closedir(dirp); + exit(0); +} + +int main(int argc, char* argv[]) +{ + //ARGUMENTS TEST + if(argc != 2) + { + printf("Usage: %s \n", argv[0]); + exit(1); + } + + if(lstdir(argv[1]) > 0) + exit(2); + + exit(0); +} diff --git a/Proj2/API_cap6.pdf b/Proj2/API_cap6.pdf new file mode 100644 index 0000000..2c0c775 Binary files /dev/null and b/Proj2/API_cap6.pdf differ diff --git a/Proj2/CarPark_assistant/README b/Proj2/CarPark_assistant/README new file mode 100644 index 0000000..80c24a7 --- /dev/null +++ b/Proj2/CarPark_assistant/README @@ -0,0 +1,12 @@ +Para responder aos requisitos anunciados para o segundo projeto de SOPE, implementamos uma possível soluçao, em que desenvolvemos 2 aplicaçoes que funcionam uma em paralelo com a outra. Tentámos tornar o código simples, eficiente, elegante e de fácil compreensão. + +As principais aplicações são as seguintes: + +parque: É responsavel por criar criar 4 theards controladores, referente aos 4 pontos de entrada e saida de viatura. Para além disso, por cada viatura criada pelo gerador, cria um thread que irá acompanhar o ciclo de vida da viatura, desde a entrada no parque até à respetiva saida. +Neste programa tentamos reduzir ao máximo a complexidade e a quantidade de código dentro da zona crítica dos mutexes, de modo o tornar o programa mais eficiente. Adicionalmente, também usámos a função sleep para representar o tempo de abertura do parque. Deste modo é possível esperar pelo tempo designado de abertura do parque, sem necessitar de consumir CPU. + + +gerador: É responsavel por criar viaturas com uma determinada frequência durante um intervalo de tempo, ditados pelos argumentos dados pelos utilizadores. O comportamento do código está de acordo com as especificações do enunciado. + +É de notar que se utilizou um semáforo na escrita para o FIFO do parque, para, deste modo, garantirmos que não ficam processos pendentes ou que recebam informações erradas. + diff --git a/Proj2/CarPark_assistant/Untitled Document b/Proj2/CarPark_assistant/Untitled Document new file mode 100644 index 0000000..0b4858d --- /dev/null +++ b/Proj2/CarPark_assistant/Untitled Document @@ -0,0 +1,6 @@ +Cristiana Ronalda pah ,,, se fores estudar diz , ya ? + +xxau + + +e enviar o video para o Best e nuno cr run on the progrma diff --git a/Proj2/CarPark_assistant/bin/gerador b/Proj2/CarPark_assistant/bin/gerador new file mode 100644 index 0000000..8e05df0 Binary files /dev/null and b/Proj2/CarPark_assistant/bin/gerador differ diff --git a/Proj2/CarPark_assistant/makefile b/Proj2/CarPark_assistant/makefile new file mode 100644 index 0000000..af82091 --- /dev/null +++ b/Proj2/CarPark_assistant/makefile @@ -0,0 +1,16 @@ +CC = gcc +CFLAGS = -Wall -D_REENTRANT +LIBS = -lpthread +OBJECTS_GER_DEP = src/gerador.c src/utils.c src/utils.h src/defines.h +OBJECTS_PAR_DEP = src/parque.c src/utils.c src/utils.h src/defines.h +OBJECTS_GER = src/gerador.c src/utils.c +OBJECTS_PAR = src/parque.c src/utils.c + +all: bin/gerador bin/parque + +bin/gerador: $(OBJECTS_GER_DEP) + $(CC) $(CFLAGS) $(OBJECTS_GER) -o bin/gerador $(LIBS) + +bin/parque: $(OBJECTS_PAR_DEP) + $(CC) $(CFLAGS) $(OBJECTS_PAR) -o bin/parque $(LIBS) + diff --git a/Proj2/CarPark_assistant/src/defines.h b/Proj2/CarPark_assistant/src/defines.h new file mode 100644 index 0000000..9173cbd --- /dev/null +++ b/Proj2/CarPark_assistant/src/defines.h @@ -0,0 +1,33 @@ +#ifndef COMMON_H +#define COMMON_H + +#include + +#define NUM_CONTROLLERS 4 +#define CONTROLLER_NAME_LEN 50 +#define VEHICLE_NAME_LEN 100 +#define MESSAGE_LEN 100 + +const char ACCEPTED_STR[] = "entrada"; +const char FULL_STR[] = "cheio!"; +const char EXITING_STR[] = "saida"; +const char CLOSED_STR[] = "encerrado"; + +const char SEM_NAME[] = "/semaphoresync"; + +char* controller_name[NUM_CONTROLLERS] = {"/tmp/fifoN", "/tmp/fifoE", "/tmp/fifoS", "/tmp/fifoO"}; + + +typedef struct { + clock_t parking_time; + int vehicle_id; + char vehicle_fifo_name[VEHICLE_NAME_LEN]; +} info_t; + + +typedef struct { + char msg[MESSAGE_LEN]; +} feedback_t; + + +#endif diff --git a/Proj2/CarPark_assistant/src/gerador.c b/Proj2/CarPark_assistant/src/gerador.c new file mode 100644 index 0000000..791d054 --- /dev/null +++ b/Proj2/CarPark_assistant/src/gerador.c @@ -0,0 +1,268 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "defines.h" +#include "utils.h" + + +#define PARK_TIME_MULTIPLES 10 +#define LOGGER_NAME "gerador.log" + + +const char VEHICLE_FIFO_PREFIX[] = "/tmp/fifo_vh"; +static FILE* fp_logger; + + +typedef struct { + char controller_fifo_name[CONTROLLER_NAME_LEN]; + info_t info; +} vehicle_t; + + +/* Global Variables */ +static int tGeracao; +static clock_t uRelogio; +static clock_t start; +static sem_t* sem; + +/* Functions */ +void* veiculo(void* arg); +vehicle_t create_vehicle(int ID); +void wait_ticks_random(); +FILE* init_logger(char* name); +int generator_log(vehicle_t vehicle, const char* status); +int generator_log_with_lifespan(vehicle_t vehicle, const char* status, clock_t lifespan); + + +int main(int argc, char **argv) +{ + double timeElapsed = 0; + int vehicleID = 0; + vehicle_t* vehicle; + + pthread_t detach_thread; + + srand(time(NULL)); + + if (argc != 3) + { + fprintf(stderr, "Usage: gerador \n"); + exit(1); + } + + if (convert_str_to_int(argv[1], &tGeracao) == -1) + { + fprintf(stderr, "Invalid entry for T_GERACAO\n"); + exit(2); + } + + if (convert_str_to_int(argv[2], (int *) &uRelogio) == -1) + { + fprintf(stderr, "Invalid entry for U_RELOGIO\n"); + exit(3); + } + + if ( (fp_logger = init_logger(LOGGER_NAME)) == NULL ) + { + fprintf(stderr, "Error opening %s\n", LOGGER_NAME); + exit(4); + } + + + if ( (sem = init_sem(SEM_NAME)) == SEM_FAILED ) + { + exit(5); + } + + start = clock(); + while (timeElapsed < tGeracao) + { + vehicle = malloc(sizeof(vehicle_t)); + *vehicle = create_vehicle(vehicleID++); + + wait_ticks_random(); + + pthread_create(&detach_thread, NULL, veiculo, vehicle); + + timeElapsed = (double) (clock() - start) / CLOCKS_PER_SEC; + } + + pthread_exit(0); +} + + + + +void* veiculo(void* arg) { + vehicle_t vehicle; + int fd_vehicle, fd_controller; + feedback_t feedback; + clock_t lifespan_start, lifespan_diff; + + + pthread_detach(pthread_self()); + vehicle = *(vehicle_t *) arg; + lifespan_start = clock(); + + + if ( (fd_vehicle = init_fifo(vehicle.info.vehicle_fifo_name, O_RDWR)) == -1 ) { + free(arg); + return NULL; + } + + /* Zona Critica */ + sem_wait(sem); + + if ( (fd_controller = open(vehicle.controller_fifo_name, O_WRONLY | O_NONBLOCK)) == -1 ) + { + generator_log(vehicle, CLOSED_STR); + + unlink_fifo(vehicle.info.vehicle_fifo_name); + free(arg); + sem_post(sem); + return NULL; + } + + + if (write(fd_controller, &vehicle.info, sizeof(vehicle.info)) == -1) + { + perror("Error writing to controller"); + unlink_fifo(vehicle.info.vehicle_fifo_name); + close(fd_controller); + free(arg); + sem_post(sem); + return NULL; + } + + close(fd_controller); + + sem_post(sem); + /***************/ + + + if (read(fd_vehicle, &feedback, sizeof(feedback)) == -1) + { + perror("Error reading controller's feedback"); + unlink_fifo(vehicle.info.vehicle_fifo_name); + close(fd_vehicle); + free(arg); + return NULL; + } + + + generator_log(vehicle, feedback.msg); + + if (strcmp(feedback.msg, ACCEPTED_STR) == 0) + { + if (read(fd_vehicle, &feedback, sizeof(feedback)) == -1) + { + perror("Error reading controller's second feedback"); + unlink_fifo(vehicle.info.vehicle_fifo_name); + close(fd_vehicle); + free(arg); + return NULL; + } + + lifespan_diff = clock() - lifespan_start; + generator_log_with_lifespan(vehicle, feedback.msg, lifespan_diff + vehicle.info.parking_time); + } + + close(fd_vehicle); + free(arg); + unlink_fifo(vehicle.info.vehicle_fifo_name); + return NULL; +} + + + + + + +vehicle_t create_vehicle(int ID) { + vehicle_t vehicle; + + strcpy(vehicle.controller_fifo_name, controller_name[rand() % NUM_CONTROLLERS]); // generate entry point (controller) + vehicle.info.vehicle_id = ID; // set ID + vehicle.info.parking_time = uRelogio * ( (rand() % PARK_TIME_MULTIPLES) + 1 ); // time in the parking lot + sprintf(vehicle.info.vehicle_fifo_name, "%s_%d", VEHICLE_FIFO_PREFIX, ID); // sets vehicle's fifo name + + return vehicle; +} + + + +void wait_ticks_random() { + int generateTimeGap, p; + + p = rand() % 10; // wait probability + if (p < 5) + generateTimeGap = 0; + else if (p < 8) + generateTimeGap = 1; + else + generateTimeGap = 2; + + wait_ticks(generateTimeGap * uRelogio); +} + + + + +FILE* init_logger(char* name) { + FILE* fp; + + if ( (fp = fopen(name, "w")) == NULL ) + return NULL; + + fprintf(fp, "t(ticks) ; id_viat ; destin ; t_estacion ; t_vida ; observ\n"); + + return fp; +} + + + +int generator_log(vehicle_t vehicle, const char* status) { + char log_msg[LOG_LENGTH]; + + sprintf(log_msg, "%8ld ; %7d ; %4c ; %10ld ; %6s ; %s\n", + clock() - start, + vehicle.info.vehicle_id, + vehicle.controller_fifo_name[strlen(vehicle.controller_fifo_name) - 1], + vehicle.info.parking_time, + "?", + status + ); + + return Log(fp_logger, log_msg); +} + + + + +int generator_log_with_lifespan(vehicle_t vehicle, const char* status, clock_t lifespan) { + char log_msg[LOG_LENGTH]; + char lifespan_str[100]; // string where lifespan will be stored + + + sprintf(lifespan_str, "%ld", lifespan); + + sprintf(log_msg, "%8ld ; %7d ; %4c ; %10ld ; %6s ; %s\n", + clock() - start, + vehicle.info.vehicle_id, + vehicle.controller_fifo_name[strlen(vehicle.controller_fifo_name) - 1], + vehicle.info.parking_time, + lifespan_str, + status + ); + + return Log(fp_logger, log_msg); +} diff --git a/Proj2/CarPark_assistant/src/makefile b/Proj2/CarPark_assistant/src/makefile new file mode 100644 index 0000000..bad2fe9 --- /dev/null +++ b/Proj2/CarPark_assistant/src/makefile @@ -0,0 +1,15 @@ +CC = gcc +CFLAGS = -Wall -D_REENTRANT +LIBS = -lpthread +OBJECTS_GER_DEP = src/gerador.c src/utils.c src/utils.h src/common.h +OBJECTS_PAR_DEP = src/parque.c src/utils.c src/utils.h src/common.h +OBJECTS_GER = src/gerador.c src/utils.c +OBJECTS_PAR = src/parque.c src/utils.c + +all: bin/gerador bin/parque + +bin/gerador: $(OBJECTS_GER_DEP) + $(CC) $(CFLAGS) $(OBJECTS_GER) -o bin/gerador $(LIBS) + +bin/parque: $(OBJECTS_PAR_DEP) + $(CC) $(CFLAGS) $(OBJECTS_PAR) -o bin/parque $(LIBS) \ No newline at end of file diff --git a/Proj2/CarPark_assistant/src/park.c b/Proj2/CarPark_assistant/src/park.c new file mode 100644 index 0000000..ace2136 --- /dev/null +++ b/Proj2/CarPark_assistant/src/park.c @@ -0,0 +1,263 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "utils.h" + +#define NUM_CONTROLLERS 4 +#define LOGGER_NAME "parque.log" + +const char FINISH_STR[] = "ACABAR"; + +const char LOG_ACCEPTED_STR[] = "estacionamento"; +const char LOG_FULL_STR[] = "cheio"; +const char LOG_EXITING_STR[] = "saida"; +const char LOG_CLOSED_STR[] = "encerrado"; + + +/* Global Variables */ +static clock_t start; +static int numLugares; +static int tAbertura; +static int numLugaresOcupados = 0; +static pthread_mutex_t arrumador_lock = PTHREAD_MUTEX_INITIALIZER; +static FILE* fp_logger; +static sem_t* sem; + + +/* Functions */ +void* controlador(void* arg); +void* arrumador(void* arg); +void notify_controllers(const char* message); +int notify_pending_vehicles(int fd_controller); +FILE* init_logger(char* name); +int park_log(info_t info, const char* status); + + +int main(int argc, char** argv) { + + pthread_t threads[NUM_CONTROLLERS]; + + if (argc != 3) + { + fprintf(stderr, "Usage: parque \n"); + exit(1); + } + + + if (convert_str_to_int(argv[1], &numLugares) != 0) + { + fprintf(stderr, "Invalid entry for N_LUGARES\n"); + exit(2); + } + + if (convert_str_to_int(argv[2], &tAbertura) != 0) + { + fprintf(stderr, "Invalid entry for T_ABERTURA\n"); + exit(3); + } + + if ( (fp_logger = init_logger(LOGGER_NAME)) == NULL ) + { + fprintf(stderr, "Error opening %s\n", LOGGER_NAME); + exit(4); + } + + if ( (sem = init_sem(SEM_NAME)) == SEM_FAILED ) + { + exit(5); + } + + start = clock(); + + int i; + for (i = 0; i < NUM_CONTROLLERS; i++) + { + pthread_create(&threads[i], NULL, controlador, controller_name[i]); + } + + sleep(tAbertura); + + /* Zona Critica */ + sem_wait(sem); + + notify_controllers(FINISH_STR); + + for (i = 0; i < NUM_CONTROLLERS; i++) + pthread_join(threads[i], NULL); + + sem_post(sem); + /***************/ + + destroy_sem(sem, SEM_NAME); + + fclose(fp_logger); + pthread_exit(0); +} + + + + +void* controlador(void* arg) { + char* fifo_name; + int fd, ret; + pthread_t detach_thread; + info_t* request_info; + + + fifo_name = (char *) arg; + + if ( (fd = init_fifo(fifo_name, O_RDONLY)) == -1 ) + pthread_exit(NULL); + + + while (1) { + request_info = (info_t *) malloc(sizeof(info_t)); + + ret = read(fd, request_info, sizeof(*request_info)); + + if (ret > 0) + { + if (strcmp(request_info->vehicle_fifo_name, FINISH_STR) == 0) + break; + + pthread_create(&detach_thread, NULL, arrumador, request_info); + } + else if (ret == -1) + { + perror("Error reading on controller"); + free(request_info); + close(fd); + unlink_fifo(fifo_name); + return NULL; + } + } + + close(fd); + unlink_fifo(fifo_name); + pthread_exit(NULL); +} + + + +void* arrumador(void* arg) { + info_t info; + int fd_vehicle; + int accepted = 0; + feedback_t feedback; + + + pthread_detach(pthread_self()); + info = *(info_t *) arg; + + + if ( (fd_vehicle = open(info.vehicle_fifo_name, O_WRONLY)) == -1 ) + { + perror(strcat(info.vehicle_fifo_name, " FIFO opening failed on arrumador")); + free(arg); + return NULL; + } + + // Validar entrada (Zona critica) + pthread_mutex_lock(&arrumador_lock); + + if (numLugaresOcupados < numLugares) + { + accepted = 1; + numLugaresOcupados++; + strcpy(feedback.msg, ACCEPTED_STR); + park_log(info, LOG_ACCEPTED_STR); + } + else { + strcpy(feedback.msg, FULL_STR); + park_log(info, LOG_FULL_STR); + } + + pthread_mutex_unlock(&arrumador_lock); + /*********************************/ + + write(fd_vehicle, &feedback, sizeof(feedback)); + + if (accepted) + { + feedback_t exit_feedback; + + // Esperar + wait_ticks(info.parking_time); + + // Validar saida (Zona critica) + pthread_mutex_lock(&arrumador_lock); + + numLugaresOcupados--; + strcpy(exit_feedback.msg, EXITING_STR); + park_log(info, LOG_EXITING_STR); + + pthread_mutex_unlock(&arrumador_lock); + /*********************************/ + + write(fd_vehicle, &exit_feedback, sizeof(exit_feedback)); + } + + + free(arg); + close(fd_vehicle); + return NULL; +} + + + + + +void notify_controllers(const char* message) { + int fd; + info_t info; + + strcpy(info.vehicle_fifo_name, message); + + int i; + for (i = 0; i < NUM_CONTROLLERS; i++) + { + if ( (fd = open(controller_name[i], O_WRONLY)) == -1 ) + { + perror("Error notifying controllers"); + return; + } + + write(fd, &info, sizeof(info)); + close(fd); + } +} + + +FILE* init_logger(char* name) { + FILE* fp; + + if ( (fp = fopen(name, "w")) == NULL ) + return NULL; + + fprintf(fp, "t(ticks) ; nlug ; id_viat ; observ\n"); + + return fp; +} + + + +int park_log(info_t info, const char* status) { + char log_msg[LOG_LENGTH]; + + sprintf(log_msg, "%8ld ; %4d ; %7d ; %s\n", + clock() - start, + numLugaresOcupados, + info.vehicle_id, + status); + + return Log(fp_logger, log_msg); +} diff --git a/Proj2/CarPark_assistant/src/utils.c b/Proj2/CarPark_assistant/src/utils.c new file mode 100644 index 0000000..0ec02a3 --- /dev/null +++ b/Proj2/CarPark_assistant/src/utils.c @@ -0,0 +1,147 @@ +#include "utils.h" + + +static int ERROR_MSG_LEN = 200; +//static int MICROSECOND_MULTIPLIER = 1000000; + + +/* + * strtol man page: + * + * "Since strtol() can legitimately return 0, LONG_MAX, or LONG_MIN + * on both success and failure, + * the calling program should set errno to 0 before the call, and then + * determine if an error occurred by checking whether errno has a + * nonzero value after the call." + */ +int convert_str_to_int(char* str, int* num) { + + int i = 0; + while (str[i] != '\0') + { + if (str[i] >= '1' && str[i] <= '9') + break; + + i++; + } + + if (i == strlen(str)) + return -1; + + errno = 0; + *num = strtol(str, NULL, 10); + if (errno != 0) + return -1; + + return 0; +} + + +/* Waits 'wait_time' ticks */ +void wait_ticks(clock_t wait_time) { + clock_t start, diff; + + start = clock(); + diff = clock(); + while ((diff - start) < wait_time) + diff = clock(); +} + + + + +/* Creates and opens FIFO */ +int init_fifo(char* fifo_name, int oflags) { + int fd; + char msg[ERROR_MSG_LEN]; + + if (mkfifo(fifo_name, S_IWUSR | S_IRUSR) == -1) + { + sprintf(msg, "FIFO %s creation failed", fifo_name); + perror(msg); + return -1; + } + + if ( (fd = open(fifo_name, oflags)) == -1 ) + { + sprintf(msg, "FIFO %s opening failed", fifo_name); + perror(msg); + unlink_fifo(fifo_name); + return -1; + } + + return fd; +} + + + +/* Handles unlink */ +int unlink_fifo(char* fifo_name) { + char msg[ERROR_MSG_LEN]; + + if (unlink(fifo_name) == -1) + { + sprintf(msg, "FIFO %s unlink failed", fifo_name); + perror(msg); + return -1; + } + + return 0; +} + + + + +int Log(FILE* fp, const char* message) { + return fprintf(fp, "%s", message); +} + + + +sem_t* init_sem(const char* name) { + sem_t* sem; + int just_open = 0; + + if( (sem = sem_open(name, O_CREAT | O_EXCL, S_IWUSR | S_IRUSR, 1)) == SEM_FAILED ) + { + if (errno == EEXIST) + just_open = 1; + else + { + perror("Error creating semaphore"); + return SEM_FAILED; + } + } + + + if (just_open) { + if( (sem = sem_open(name, 0)) == SEM_FAILED ) + { + perror("Error opening semaphore"); + return SEM_FAILED; + } + } + + return sem; +} + + + + +int destroy_sem(sem_t* sem, const char* name) { + + if (sem_close(sem) == -1) + { + perror("Error closing semaphore"); + return -1; + } + + + if (sem_unlink(name) == -1) + { + perror("Error unlinking semaphore"); + return -1; + } + + return 0; +} diff --git a/Proj2/CarPark_assistant/src/utils.h b/Proj2/CarPark_assistant/src/utils.h new file mode 100644 index 0000000..7273baa --- /dev/null +++ b/Proj2/CarPark_assistant/src/utils.h @@ -0,0 +1,26 @@ +#ifndef UTILS_H +#define UTILS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LOG_LENGTH 1024 + +int convert_str_to_int(char* str, int* num); +void wait_ticks(clock_t wait_time); +int init_fifo(char* fifo_name, int oflags); +int unlink_fifo(char* fifo_name); +int Log(FILE* fp, const char* message); +sem_t* init_sem(const char* name); +int destroy_sem(sem_t* sem, const char* name); + +#endif diff --git a/Proj2/Projecto2/src/Untitled Document b/Proj2/Projecto2/src/Untitled Document new file mode 100644 index 0000000..e730586 --- /dev/null +++ b/Proj2/Projecto2/src/Untitled Document @@ -0,0 +1,11 @@ +Para responder aos requisitos anunciados para o segundo projeto de SOPE, implementamos uma possível soluçao, em que desenvolvemos 2 aplicaçoes que funcionam uma em paralelo com a outra. Tentámos tornar o código simples, eficiente, elegante e de fácil compreensão. + +As principais aplicações são as seguintes: + +parque: É responsavel por criar criar 4 theards controladores, referente aos 4 pontos de entrada e saida de viatura. Para além disso, por cada viatura criada pelo gerador, cria um thread que irá acompanhar o ciclo de vida da viatura, desde a entrada no parque até à respetiva saida. +Neste programa tentamos reduzir ao máximo a complexidade e a quantidade de código dentro da zona crítica dos mutexes, de modo o tornar o programa mais eficiente. Adicionalmente, também usámos a função sleep para representar o tempo de abertura do parque. Deste modo é possível esperar pelo tempo designado de abertura do parque, sem necessitar de consumir CPU. + + +gerador: É responsavel por criar viaturas com uma determinada frequência durante um intervalo de tempo, ditados pelos argumentos dados pelos utilizadores. O comportamento do código está de acordo com as especificações do enunciado. + +É de notar que se utilizou um semáforo na escrita para o FIFO do parque, para, deste modo, garantirmos que não ficam processos pendentes ou que recebam informações erradas. diff --git a/Proj2/Projecto2/src/defines.h b/Proj2/Projecto2/src/defines.h new file mode 100644 index 0000000..9719db6 --- /dev/null +++ b/Proj2/Projecto2/src/defines.h @@ -0,0 +1,26 @@ +#define FIFON "/tmp/fifoN" +#define FIFOS "/tmp/fifoS" +#define FIFOW "/tmp/fifoO" +#define FIFOE "/tmp/fifoE" + +#define GENERATOR_LOG "generate_log.log" +#define PARK_LOG "park_log.log" +#define LOG "general_log.log" + +#define ENTERING 1 +#define EXITING 2 +#define FULL -1 +#define CLOSED -2 + +#define MAX_BUF 64 +#define LONG_BUF 256 + +typedef struct +{ + int id; + char port; + double park_time; + long initial_tick; + char fifo[MAX_BUF]; + long tps; +} Vehicle; diff --git a/Proj2/Projecto2/src/generator.c b/Proj2/Projecto2/src/generator.c new file mode 100644 index 0000000..ac70ffa --- /dev/null +++ b/Proj2/Projecto2/src/generator.c @@ -0,0 +1,55 @@ +// thread viatura do lado gerador +// thread controlador thread do lado do park + +//tcontroller +closed = 0; + + + +fd= open(FIFON, O_RDONLY)// cada um c/ 1 fifo diferente referente a porta 9 e digo abre read-only: +while (read(fd, ,)!=0) +{ + if (closed) + // mandar mensagem 'fechado' + + if ( id == 0) + closed = 1; +} + +// nem sempre a gerar veículos, durante isso espero uns ticks. +// cada fifo que esta a entrada do patio e .. etc + +// aqui qdo este ciclo termina envio um ciclo qdo irá ser igual a 0 + +// qdo o parque está a zero o FIFO está bloqueado !! +// se já existir um fifo a tentar enviar a mensagem existe 1... logo que a thread a fechar o FIFO aberto existirá um fifo a retornar algo aberto!! + +//algo a retornar do lado do gerador + + +// criação de thread veiculos para cada um desses veiculos, que é : cria fifo de terminar qdo o parque fechar!! +// cria um flag +tvehicle + + + +fd = open(FIFO...., O_wronly|O_NONBLOCK) +// qdo aberto para leitura sei que o parque já ta fechado e já não crio nada e... +if (fd!= -1) +{ +// e logo qdo façço o write logo a seguir faço o close e por aí fora... + write(..., vehicle, ...); + // conjugação destas coisas todas até que o parque não tenha gerador + close(fd); +} + +if (fd == -1) + // parque fechado (lado leitura está fechado) + +// 1 handler para o sig_PIPE que nos indica essa hipotese! + +// semafero partilhado nos 2 programas!! + + // programas independentes 1 do outro, + //o gerador a gerar carros o parque funciona ... poem la o carro e: +// gerar um numa altura e outro noutra e versão simplificada e o tempo que existem podem ser maior ou menor! diff --git a/Proj2/Projecto2/src/park.c b/Proj2/Projecto2/src/park.c new file mode 100644 index 0000000..8c472f3 --- /dev/null +++ b/Proj2/Projecto2/src/park.c @@ -0,0 +1,222 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "defines.h" + +int free_places; +int closed; + +void * tpark_helper(void * avg) +{// veicule é uma thread que contém um fifo + + Vehicle vehicle = *(Vehicle *) avg; + int fd_write; + int park_state = 0; + + pthread_detach(pthread_self()); + + fd_write = open(vehicle.fifo, O_WRONLY); + + if(free_places > 0 && closed != 1) + { + park_state = ENTERING; + write(fd_write, &park_state, sizeof(int)); + free_places--; + sleep(vehicle.park_time); + free_places++; + park_state = EXITING; + write(fd_write, &park_state, sizeof(int)); + } + else if(closed == 1) + { + park_state = CLOSED; + write(fd_write, &park_state, sizeof(int)); + } + else if(free_places <= 0) + { + park_state = FULL; + write(fd_write, &park_state, sizeof(int)); + } + + + close(fd_write); + return NULL; +} + +void * tcontroller_N(void * avg) +{ + int fd; + Vehicle vehicle; + + mkfifo(FIFON, 0600); + fd = open(FIFON, O_RDONLY); + + + while(read(fd, &vehicle, sizeof(vehicle)) != 0) + { + if(vehicle.id == -1) + { + break; + } + else + { + pthread_t tid; + pthread_create(&tid, NULL, tpark_helper, &vehicle); // fazer um open para este mesmo fifo com 1 open por wronly + fd = open(FIFON, O_WRONLY); // car_assistant + } // significa que chega um carro para fechar o parque.. + }// reservo um id dos automoveis para reservar o parque! +// parque aberto durante um certo periodo sleep (duration) +// algures se recebo 1 veículo c/ um id = 0 tenho: de fechar o parque + + sleep(duration); + close(fd); + pthread_exit(0); + return NULL; +} + +void * tcontroller_E(void * avg) +{ + int fd; + Vehicle vehicle; + + mkfifo(FIFOE, 0600); + fd = open(FIFOE, O_RDONLY); + + while(read(fd, &vehicle, sizeof(vehicle)) != 0) + { + if(vehicle.id == -1) + { + break; + } + else + { + pthread_t tid; + pthread_create(&tid, NULL, tpark_helper, &vehicle); + } + } + + + close(fd); + pthread_exit(0); + return NULL; +} + +void * tcontroller_W(void * avg) +{ + int fd; + Vehicle vehicle; + + mkfifo(FIFOW, 0600); + fd = open(FIFOW, O_RDONLY); + + while(read(fd, &vehicle, sizeof(vehicle)) != 0) + { + if(vehicle.id == -1) + { + break; + } + else + { + pthread_t tid; + pthread_create(&tid, NULL, tpark_helper, &vehicle); + } + } + + + close(fd); + pthread_exit(0); + return NULL; +} + +void * tcontroller_S(void * avg) +{ + int fd; + Vehicle vehicle; + + mkfifo(FIFOS, 0600); + fd = open(FIFOS, O_RDONLY); + + while(read(fd, &vehicle, sizeof(vehicle)) != 0) + { + if(vehicle.id == -1) + { + break; + } + else + { + pthread_t tid; + pthread_create(&tid, NULL, tpark_helper, &vehicle); + } + } + + close(fd); + pthread_exit(0); + return NULL; +} + +int main(int argc, const char * argv[]) +{ + //variables declaration + int fplaces; + int duration; + int fdN, fdS, fdW, fdE; + pthread_t tidN, tidS, tidW, tidE; + Vehicle* vehicle_stop = (Vehicle*) malloc(sizeof(Vehicle)); + + //test arguments + if(argc != 3) + { + printf("Usage %s \n", argv[0]); + free(vehicle_stop); + return 1; + } + + //variable initialization + free_places = fplaces = atoi(argv[1]); + duration = atoi(argv[2]); + + //creating threads and executing + pthread_create(&tidN, NULL, tcontroller_N, NULL); + pthread_create(&tidS, NULL, tcontroller_S, NULL); + pthread_create(&tidW, NULL, tcontroller_W, NULL); + pthread_create(&tidE, NULL, tcontroller_E, NULL); + + closed = 0; + sleep(duration); + closed = 1; + + //creating the stop vehicle and closing program + vehicle_stop->id = -1; + fdN = open(FIFON, O_WRONLY); + fdS = open(FIFOS, O_WRONLY); + fdW = open(FIFOW, O_WRONLY); + fdE = open(FIFOE, O_WRONLY); + write(fdN, &vehicle_stop, sizeof(Vehicle)); + write(fdS, &vehicle_stop, sizeof(Vehicle)); + write(fdW, &vehicle_stop, sizeof(Vehicle)); + write(fdE, &vehicle_stop, sizeof(Vehicle)); + free(vehicle_stop); + close(fdN); + close(fdS); + close(fdW); + close(fdE); + unlink(FIFON); + unlink(FIFOS); + unlink(FIFOW); + unlink(FIFOE); + + + pthread_join(tidN,NULL); + pthread_join(tidS,NULL); + pthread_join(tidW,NULL); + pthread_join(tidE,NULL); + + pthread_exit(NULL); + return 0; +} diff --git a/Proj2/SOPE-1516-TP2-v4.2.pdf b/Proj2/SOPE-1516-TP2-v4.2.pdf new file mode 100644 index 0000000..731733c Binary files /dev/null and b/Proj2/SOPE-1516-TP2-v4.2.pdf differ diff --git a/Proj2/dica.png b/Proj2/dica.png new file mode 100644 index 0000000..e96c1ec Binary files /dev/null and b/Proj2/dica.png differ diff --git a/Proj2/makefile b/Proj2/makefile new file mode 100644 index 0000000..b04765a --- /dev/null +++ b/Proj2/makefile @@ -0,0 +1,15 @@ +CC = gcc +CFLAGS = -Wall -D_REENTRANT +LIBS = -lpthread +OBJECTS_GER_DEP = src/generator.c src/defines.h +OBJECTS_PAR_DEP = src/park.c src/defines.h +OBJECTS_GER = src/gerador.c +OBJECTS_PAR = src/park.c + +all: bin/generator bin/park + +bin/generator: $(OBJECTS_GER_DEP) + $(CC) $(CFLAGS) $(OBJECTS_GER) -o bin/generator $(LIBS) + +bin/park: $(OBJECTS_PAR_DEP) + $(CC) $(CFLAGS) $(OBJECTS_PAR) -o bin/park $(LIBS) diff --git a/Proj2/makefile~ b/Proj2/makefile~ new file mode 100644 index 0000000..b04765a --- /dev/null +++ b/Proj2/makefile~ @@ -0,0 +1,15 @@ +CC = gcc +CFLAGS = -Wall -D_REENTRANT +LIBS = -lpthread +OBJECTS_GER_DEP = src/generator.c src/defines.h +OBJECTS_PAR_DEP = src/park.c src/defines.h +OBJECTS_GER = src/gerador.c +OBJECTS_PAR = src/park.c + +all: bin/generator bin/park + +bin/generator: $(OBJECTS_GER_DEP) + $(CC) $(CFLAGS) $(OBJECTS_GER) -o bin/generator $(LIBS) + +bin/park: $(OBJECTS_PAR_DEP) + $(CC) $(CFLAGS) $(OBJECTS_PAR) -o bin/park $(LIBS) diff --git a/TutoriasLegais b/TutoriasLegais new file mode 100644 index 0000000..babe770 --- /dev/null +++ b/TutoriasLegais @@ -0,0 +1,2 @@ +Este e um arquivo chamado(com ou sem caminho e formato): +TutoriasLegais diff --git a/a01p01 b/a01p01 new file mode 100644 index 0000000..9744f03 Binary files /dev/null and b/a01p01 differ diff --git a/a01p01.c b/a01p01.c new file mode 100644 index 0000000..58882c1 --- /dev/null +++ b/a01p01.c @@ -0,0 +1,11 @@ + + #include + + int main(void) +{ + int y = 65; + char x; + + x = (char) y; + printf("O numero inteiro: %d \n O caracter: %c \n\n", y, x); + } diff --git a/a3#1 b/a3#1 new file mode 100644 index 0000000..cea5568 Binary files /dev/null and b/a3#1 differ diff --git a/a3#1.c b/a3#1.c new file mode 100644 index 0000000..9e03396 --- /dev/null +++ b/a3#1.c @@ -0,0 +1,15 @@ +#include +int +main () +{ + int indice; + printf ("Indice da qualidade do ar:"); + scanf ("%d", &indice); + if (indice < 35) + printf ("Boa\n"); + else if (indice >= 35 && indice <= 60) + printf ("Má\n"); + else + printf ("Péssima\n"); + return 0; +} diff --git a/a3#1.c~ b/a3#1.c~ new file mode 100644 index 0000000..d4002de --- /dev/null +++ b/a3#1.c~ @@ -0,0 +1,12 @@ +#include +int main() { +int indice; +printf("Indice da qualidade do ar:"); +scanf("%d",&indice); +if (indice < 35) + printf("Boa\n"); +else if( indice >= 35 && indice <= 60) + printf("Má\n"); +else printf("Péssima\n"); +return 0; +} diff --git a/abs b/abs new file mode 100644 index 0000000..75cfa26 Binary files /dev/null and b/abs differ diff --git a/abs.c b/abs.c new file mode 100644 index 0000000..f955d66 --- /dev/null +++ b/abs.c @@ -0,0 +1,12 @@ +#include +#include + +int main() + { + int nr1 = 5,nr2 = -7; + + printf("\n"); + printf("nr1=%d\tabs(nr1)=%d\n",nr1,abs(nr1)); + printf("nr2=%d\tabs(nr2)=%d\n\n",nr2,abs(nr2)); + return(0); + } diff --git a/abs.o b/abs.o new file mode 100644 index 0000000..4c12d3e Binary files /dev/null and b/abs.o differ diff --git a/amor b/amor new file mode 100644 index 0000000..6d2017c Binary files /dev/null and b/amor differ diff --git a/apontadornulo b/apontadornulo new file mode 100644 index 0000000..064a63b Binary files /dev/null and b/apontadornulo differ diff --git a/apontadornulo.c b/apontadornulo.c new file mode 100644 index 0000000..93ec307 --- /dev/null +++ b/apontadornulo.c @@ -0,0 +1,20 @@ +int main(void) +{ + //int x= 91; + char *p1 = (char *) malloc(sizeof(char)); // aloca memória e inicializa o ponteiro + printf("p1 aponta para: %p\n", p1); // aponta para algum lugar da memória heap + printf("Valor de *p1: %c\n", *p1); // valor (indefinido) de algum lugar na memória heap + + char *p2; // ponteiro selvagem + printf("Endereco de p2: %p\n", p2); // valor indefinido, pode não ser um endereço válido + //char *p3 = &x; + //printf("Endereco de p3: %p\n", p3); + // mas se fizzesse: + // se você for sortudo, isso irá causar uma exceção de endereçamento + printf("Valor de *p2: %c\n", *p2); // valor aleatório em endereço aleatório + printf("Valor de *p3: %c\n", *p3); + + free(p1); //A função free libera o espaço de memória usado pelo ponteiro + + return 0; +} diff --git a/arquivos/ExperienciaTutor.cpp b/arquivos/ExperienciaTutor.cpp new file mode 100644 index 0000000..f891b02 --- /dev/null +++ b/arquivos/ExperienciaTutor.cpp @@ -0,0 +1,2 @@ +Este e um arquivo chamado(com ou sem caminho e formato): +arquivos/ExperienciaTutor.cpp diff --git a/arquivos/arquivo.bin b/arquivos/arquivo.bin new file mode 100644 index 0000000..d356e47 Binary files /dev/null and b/arquivos/arquivo.bin differ diff --git a/arquivos/fputs.txt b/arquivos/fputs.txt new file mode 100644 index 0000000..b74698c --- /dev/null +++ b/arquivos/fputs.txt @@ -0,0 +1,2 @@ + + Amnha o coelhinho da Páscoa vai regressar!! Value, você é o CARA!Esta é uma linguagem de programação do sistema. \ No newline at end of file diff --git a/arquivos/texto.txt b/arquivos/texto.txt new file mode 100644 index 0000000..1532677 --- /dev/null +++ b/arquivos/texto.txt @@ -0,0 +1 @@ +A função retorna o número de unidades efetivamente lidas. Este número pode ser menor que count quando o fim do arquivo for encontrado ou ocorrer algum erro. Quando o arquivo for aberto para dados binários, fread pode ler qualquer tipo de dados. diff --git a/aula10 b/aula10 new file mode 100644 index 0000000..b0f911d Binary files /dev/null and b/aula10 differ diff --git a/aula10.c b/aula10.c new file mode 100644 index 0000000..55e138b --- /dev/null +++ b/aula10.c @@ -0,0 +1,15 @@ +#include +int +main () +{ + int contador; + int numero = 1; + + for (contador = 1; contador <= 10; contador = contador + 1) + { //colchete + printf ("O programa é muito bonito\n"); + puts("Xiro"); + } + + return 0; +} diff --git a/aula10.c~ b/aula10.c~ new file mode 100644 index 0000000..307e134 --- /dev/null +++ b/aula10.c~ @@ -0,0 +1,14 @@ +#include +int +main () +{ + int contador; + int numero = 1; + + for (contador = 1; contador <= 10; contador = contador + 1) + { //colchete + printf ("O programa é muito bonito\n"); + } + + return 0; +} diff --git a/aula17 b/aula17 new file mode 100644 index 0000000..5bea441 Binary files /dev/null and b/aula17 differ diff --git a/aula17.c b/aula17.c new file mode 100644 index 0000000..9cfe977 --- /dev/null +++ b/aula17.c @@ -0,0 +1,32 @@ +#include +#include +#include + +int main(int argc, char *argv[]) +{ + int i=0; + unclock_t inicio=0,fim=0; + + inicio=uclock(); + + /*código a executar */ + + int n,fatorial=1; + printf ("fatorial de:"); + scanf ("%d", &n); + printf ("=\v%d!=",n); + while (n>=1) + { + fatorial *= n; + printf("%d*",n); + --n; + } + printf ("=%d\n",fatorial); + + + fim=uclock(); + + fprintf(stdout,"Tempo: %Ld",(fim-inicio)/(UCLOCKS_PER_SEC)); + return 0; + +} diff --git a/aula2 b/aula2 new file mode 100644 index 0000000..02c1459 --- /dev/null +++ b/aula2 @@ -0,0 +1,3 @@ +#!/bin/bash + +// script .. diff --git a/aula21 b/aula21 new file mode 100644 index 0000000..c5f3010 Binary files /dev/null and b/aula21 differ diff --git a/aula21.c b/aula21.c new file mode 100644 index 0000000..d58376b --- /dev/null +++ b/aula21.c @@ -0,0 +1,17 @@ +#include +int main(void) + { + for (int i =1; i<= 10;i=1+i) + { + printf("***Volta %i**\n", i); + for (int j =1;j<11;++j) + { + printf("Ponto %i\n",j); + } + puts(""); + } + + puts(""); + return 0; + } + diff --git a/aula22 b/aula22 new file mode 100644 index 0000000..332d75e Binary files /dev/null and b/aula22 differ diff --git a/aula22.c b/aula22.c new file mode 100644 index 0000000..2b02f21 --- /dev/null +++ b/aula22.c @@ -0,0 +1,15 @@ +#include +int main (void) + { + int nota[5];// como acessar cada bloco + + nota[0] = 50; + nota[1] = 5; + nota[2] = 4; + nota[3] = 2; + nota[4] = 7; + printf("%d\n", nota[0]); + +//nota[5] = X, não irá ser atribuído: pois o & não existe + return 0; +} diff --git a/aula23 b/aula23 new file mode 100644 index 0000000..2cd9ba4 Binary files /dev/null and b/aula23 differ diff --git a/aula23.c b/aula23.c new file mode 100644 index 0000000..28f5eb1 --- /dev/null +++ b/aula23.c @@ -0,0 +1,10 @@ +#include +int main (void) +{ + int vetor [5] = {0}; + + for (int i=0;i<=4;i++) + + printf("%d\n",vetor[i]); + getchar(); +} diff --git a/aula24 b/aula24 new file mode 100644 index 0000000..d2ce926 Binary files /dev/null and b/aula24 differ diff --git a/aula24.c b/aula24.c new file mode 100644 index 0000000..8612f8b --- /dev/null +++ b/aula24.c @@ -0,0 +1,20 @@ +#include +int main (void) +{//digitar notas,armazenar notas num vetor,calcular média e devolução do seu resultado. + int i=0; + float notas[5]; + float total = 0; + float media = 0; + + printf("Insira 5 notas\n"); + for (i=0;i<5;i++) + { + scanf("%f",¬as[i]); + total+=notas[i]; + //if (i==5) + + media = total/i; + } + printf("A media é de:%F e o total será:%3f\n" ,media,total); + return 0; +} diff --git a/aula25 b/aula25 new file mode 100644 index 0000000..a4e6b73 Binary files /dev/null and b/aula25 differ diff --git a/aula25.c b/aula25.c new file mode 100644 index 0000000..410710c --- /dev/null +++ b/aula25.c @@ -0,0 +1,18 @@ +#include +int main (void) + // Matrizes def.: extensão de vetores-> utilizar matrizes vetores muitiderecionais (com linhas e colunas) + { + int i,j; + int vetor[3]={1,2,3}; + int matriz[i][j]; + matriz[i][j]={{0,1,2},{3,4,5},{6,7,8},{9,10,11}}; //linhas e colunas respectivamente + // pode-se utilizarem matrizes tri-, qua-...dimensionais + //fazer blocos de matrizes {{1,2,3},{4,5,6},{7,8,9}}; ou ignora-se todas as chaves, ele percebe quando muda de linha :) + for (i=0;i<4;i++) + {} // acessar ao membros usando o printf, no caso de matriz temos 2 blocos de informação + for (j=0;j<5;j++) + {i+=0; + j=j; + } +return 0; +} diff --git a/aula25b b/aula25b new file mode 100644 index 0000000..cad7aa6 Binary files /dev/null and b/aula25b differ diff --git a/aula25b.c b/aula25b.c new file mode 100644 index 0000000..106be40 --- /dev/null +++ b/aula25b.c @@ -0,0 +1,29 @@ +#include + + int main (void){ + // Matrizes def.: extensão de vetores-> utilizar matrizes vetores muitiderecionais (com linhas e colunas) + + int i = 0; + int j = 0; + + int vetor[3]={1,2,3}; + int matriz[3][4]={0,1,2,3,4,5,6,7,8,9,10,11}; //linhas e colunas respectivamente + // pode-se utilizarem matrizes tri-, qua-...dimensionais + //fazer blocos de matrizes {{1,2,3},{4,5,6},{7,8,9}}; ou ignora-se todas as chaves, ele percebe quando muda de linha :) + for (i=0;i %d", vetor[i]); + } + + printf("\n\n\n"); // acessar ao membros usando o printf, no caso de matriz temos 2 blocos de informação + + for(i=0;i< 3; i++){ + for(j=0;j<4;j++){ + printf("\t\t %d", matriz[i][j]); + } + printf("\n"); + } + + printf("\n\n***Fim***\n\n "); + + return 0; + } diff --git a/aula26 b/aula26 new file mode 100644 index 0000000..3b985ee Binary files /dev/null and b/aula26 differ diff --git a/aula26.c b/aula26.c new file mode 100644 index 0000000..4085749 --- /dev/null +++ b/aula26.c @@ -0,0 +1,14 @@ +#include +int main (void) + { + int i; + while (i<=10) + { + printf("%i",i); + puts(""); + i++; + + } + + return 0; + } diff --git a/aula27 b/aula27 new file mode 100644 index 0000000..67a87d8 Binary files /dev/null and b/aula27 differ diff --git a/aula27.c b/aula27.c new file mode 100644 index 0000000..3b07369 --- /dev/null +++ b/aula27.c @@ -0,0 +1,13 @@ +#include +#define tabuada 5 +int main (void) + { + int n=0; + while (n<11) + { + printf("%d tabuada * %2i = %.3i\n",tabuada,n,tabuada*n); + n++; + + } + return 0; + } diff --git a/aula29.c b/aula29.c new file mode 100644 index 0000000..4369de7 --- /dev/null +++ b/aula29.c @@ -0,0 +1,12 @@ +#include +int main (void) +{ + float calcularAreaRetangulo(float x,float y);//declaração da variável + calcularAreaRetangulo(// copia dos valores que estão na var retangulo.. + + return 0; +} +float calcularAreaRetangulo(float x, float y) { +//calcular area quadrado +float area=base * altura; +return ; diff --git a/aula29a.c b/aula29a.c new file mode 100644 index 0000000..f04e4a5 --- /dev/null +++ b/aula29a.c @@ -0,0 +1,42 @@ + + + + + + diff --git a/aula2~ b/aula2~ new file mode 100644 index 0000000..a9bf588 --- /dev/null +++ b/aula2~ @@ -0,0 +1 @@ +#!/bin/bash diff --git a/aula4 b/aula4 new file mode 100644 index 0000000..8244613 Binary files /dev/null and b/aula4 differ diff --git a/aula4.c b/aula4.c new file mode 100644 index 0000000..412678f --- /dev/null +++ b/aula4.c @@ -0,0 +1,7 @@ +#include +int main () +{ + int myIdd = 21; + printf("A minha idade é %i \n", myIdd); + return 0; +} diff --git a/aula4.o b/aula4.o new file mode 100644 index 0000000..5d6d048 Binary files /dev/null and b/aula4.o differ diff --git a/aula60Inderetion.c b/aula60Inderetion.c new file mode 100644 index 0000000..a910e61 --- /dev/null +++ b/aula60Inderetion.c @@ -0,0 +1,5 @@ +#include +int main () + { + + diff --git a/aula9 b/aula9 new file mode 100644 index 0000000..3d4943f Binary files /dev/null and b/aula9 differ diff --git a/aula9.c b/aula9.c new file mode 100644 index 0000000..c896dc0 --- /dev/null +++ b/aula9.c @@ -0,0 +1,12 @@ +#include + +int main () +{ + int num1 = 5; + float num2 = 2; + float resultado; + resultado = num1 / num2; + + printf("O res:%f\n", resultado); + return 0; +} diff --git a/aula9.o b/aula9.o new file mode 100644 index 0000000..5abe240 Binary files /dev/null and b/aula9.o differ diff --git a/aula94-Buffer.c b/aula94-Buffer.c new file mode 100644 index 0000000..26bbe03 --- /dev/null +++ b/aula94-Buffer.c @@ -0,0 +1,20 @@ +// Limpeza de Buffer +#include +int main () + { + // funções que facilitam input ou output ... + // função getchar ... lê carater do stdin (vem do teclado) + // buffer local na memória que armazena dados até ser carregado o enter + // aperta-mos duas teclas + char a,b,c; + + a = getchar(); + b = getchar(); + c = getchar(); + + printf("%c", a); + printf("%c", b); + printf("%c", c); + + return 0; + } diff --git a/aulas b/aulas new file mode 100644 index 0000000..53fe32a Binary files /dev/null and b/aulas differ diff --git a/aulas.c b/aulas.c new file mode 100644 index 0000000..d0571d6 --- /dev/null +++ b/aulas.c @@ -0,0 +1,424 @@ +#include +/*int fatorial(int n) +{ + fatorial(n) = n*fatorial (n-1); + fatorial (1)=1; + ou + fatorial n = for (i=0;i<=n;i++); + +} +*/ +void +neg () +{ + int z = 20; + if (!z) + printf ("Código de Z vale: %d\n", z); +} + +int +draftfuction () +{ + int fatorial = 10; + int resposta = 1; + + for (; fatorial >= 1; --fatorial) + { + resposta *= fatorial; + //resposta = resposta * fatorial;5 * 4 * 3 *2 *1 + } + printf ("O numero fatorial e: %i\n", resposta); + return 0; + +} + +void +aula13 () +{ + int i = 0; + while (i != 0) + { + printf ("Teste\n"); + } + do + { + printf ("Teste do\n"); + } + while (i != 0); +} + +void +aula14 () +{ + /*int idade = 033; + int idd = 0x33; + printf("Favor informar idade:\n"); + + if (idade < 180) + + printf("A idd é:%i \te a do pai é:%d",idade,idd);//%Oi,%Oxi, + */ + int idade; + printf ("Informar idade\n"); + scanf ("%d", &idade); + + if (idade <= 5) + printf ("bebê\n"); + else if (idade > 5 && idade <= 10) + printf ("Criança\n"); + else if (idade > 10 && idade <= 18) + printf ("Adolescente\n"); + else if (idade > 18 && idade <= 50) + printf ("Adulto\n"); + else + printf ("idoso\n"); +} + +int +aula16 () +{ + /*int i; + + printf("Insira um nº inteiro de 1 a 5\n"); */ + return 0; +} + +void +exer2 () +{ + int first, second; + puts ("Digite 2 numbers.."); + scanf ("%i%d", &first, &second); + if (second == 0) + puts ("Divisão por 0 nao permitido"); + else + { + if (first % second == 0) + { + puts ("é divisível"); + printf ("E o quociente de %i por %d é:%d \n", first, second, + first / second); + } + else + puts ("not divisible"); + } +} + +void +exerc3 () // ter em conta numero Pos e Neg.. numero !0 que é qdo para +{ + int num, inverted, div = 1; + scanf ("%d", &num); + inverted = num % 10; + num /= 10; + while (num != 0) + { + inverted *= 10; + div *= 10; + inverted += num % 10; + num /= 10; + } + printf ("O número digitado é %i\n", inverted); +} + +void +aula19 () +{ + /*const */ int variavelInt = 10; + printf ("%i\n", variavelInt); + scanf ("%i", &variavelInt); + printf ("%d\n", variavelInt); + + double varD = -10.10; + printf ("%f\n", varD); + scanf ("%lf", &varD); // ao ler temos de por o Quantifier... + printf ("%f\n", varD); + +} + +void +resol16 () +{ + int i, n; + scanf ("%d", &n); + for (i = 1; i <= n; i++) // como 0 nâo aparece, então temos de ser nos a fazer o programa... + printf ("%d %d\n", i, n - i + 1); +} + +//*() +void +resol17 () +{ + int i, j, n; + char ch; + + printf ("Introd. um Nº: "); + scanf ("%d", &n); + printf ("Introd. um Char: "); + scanf (" %c", &ch); + + for (i = 1; i <= n; i++) + { + for (j = 1; j <= n; j++) + putchar (ch); + putchar ('\n'); + } +} + +void +resol18 () +{ + int num, multipl, i; + puts ("Digite um num.."); + scanf ("%d", &num); + puts ("____________"); + multipl = num / 10; + for (i = num; i < (multipl + 1) * 10; i++) + { + if (i % 3 == 0) + continue; + else + printf ("%i\n", i); + + } + putchar ('\n'); +} + +void +breakcode () +{ + int n = 33; + /* conclusion-> aulas.c:166:2: error: break statement not within loop or switch + break; + ^ + break; */ + printf ("easy pizi%i", n); +} + +void +Christmans_tree () +{ + int ramos, i, j, contador; + puts ("Digite o numero de ramos que pretende para a sua arvore"); + scanf ("%d", &ramos); + for (i = 0, contador = 0; i <= ramos; i++) // se puser i=1 não executa 1 ciclo (o dentro not satisfaz a condição) inultimente, que deixa somente 1a linha em branco + { + contador += i; + for (j = 1; j <= i; j++) + { + putchar ('*'); + + } + puts (""); // or putchar('\n'); + } + printf ("O numero de asteriscos (*) é: %d\n", contador); +} + +/* +void piramide_alfabética() +{ + int letra=65,i,j,contador; + char converte; + puts("Digite o numero de ramos que pretende para a sua arvore"); + scanf("%d",&ramos); + for (i=0,contador = 0;i<=ramos;i++) + { contador += i; + letra++; + for (j=1;j<=i;j++) + { + converte = (char) letra; + getchar(""); + putchar('',); + + } + puts(""); + } + printf("O numero de letras (*) é: %d\n",contador); +} +*/ +void +cem_first () +{ + int valor = 0; + while (valor > 100 || valor < 1) // boa cena como é que não me lembrei disto antes... utilizar o ciclo do ... while + scanf ("%d", &valor); +} + +/*int ASCIItable () +{ + int i,jan=20; + for(i=0;i<256;i++) + while (jan>0) + { + jan--; + printf("%3d --> %c\n", i,(char) i); + continue; + } + getchar('c' || 'C'); + return 0; +} + +#include */ +int +tabela_ASCCI () +{ + int i = 0; //,j=20; + char ch; // o por o J como carga init... + for (i = 1; i < 256; i++) + { + printf ("%d --> %c\n", i, (char) i); + if (i % 20 == 0) //(j>0) + { + scanf (" %c", &ch); + switch (ch) + { + case 'c': + break; //continue; + default: + puts ("Pressione c ou C, para continuar"); + + } + /* else + { + scanf(" %c",&ch); + switch(ch) + { + case 'c': break;//continue; + default: {puts ("Go out");break;} + } + } */ + //j--; + + } + } + return 0; +} + + + +int +resolp11 () +{ + int i, conta; + char ch; + for (conta = 1, i = 0; i <= 255; i = i + 1) + { + printf ("%3d --> %c\n", i, (char) i); + if (conta == 20) + { + do + { + puts ("Pressione c ou C para continuar ..."); + scanf (" %c", &ch); // para no ciclo seguinte não mandar, a mensagem pela tecla enter... + } + while (ch != 'c' && ch != 'C'); + conta = 1; + } + else + conta++; + } + return 0; +} + +int +ASCII2 () +{ + int n1, n2, Max, Min, i; + puts ("DIgite os limites do intervalo!"); + scanf ("%d%i", &n1, &n2); + if (n1 > n2) + { + Max = n1; + Min = n2; + } + else + { + Max = n2; + Min = n1; + } + i = Min; + do + { + printf (" %3d --> %c\n", i, (char) i); + i++; + } + while (i <= Max); // for <= + return 0; +} + +/* +int ASCII2Damas() +{ + int Max,min,tmp,i; + puts//("Digite os valores que pretende apresentar com limites... comece no min e depois o max\n\n//( Introd. dois Nºs: "); + scanf (" %d",&Max); scanf("%d",&min); + while( nmin<0 || nmin // outra função para este tipo de ciclo... + if (Max < min) + { + tmp= Max; + Max=min; desta forma é mais fácil to DO as trocas de valores de var's + min=tmp; + } + for(i=min;i<=Max;i++) // ou ++i + printf(" %3d --> %c\n", i, (char) i); + //printf(" Os valores corretos da variáveis necessários são: " + */ + + +void +aula30e31 () +{ + void teste (void); // desnecessário , bastava por o protótipo em cima + teste (); + teste (); + teste (); + //invalid space not recognized printf (" O valor associado é %d", variavelLocalEstatica); + + //return 0; +} + +// acesso à função variável vísivel a todas a minha funções, o modo é utilizar uma variável global ... Fora dos colchetes +int gVariavelGlobal = 2; +void +teste (void) +{ + int variavelLocalAutomatica = 2; // é recriada.. qualquer valor que tenha antes é perdido (sempre que a chamam) + variavelLocalAutomatica *= 2; + static int variavelLocalEstatica = 2; //Não perde o Valor e não fará esta Atribuição/Assignment + variavelLocalEstatica *= 2; // o valor aproveita os valores calculados em chamadas anteriores a esta função! + // differences a estática não perde o valor dela quando é chamada + // logo não é automáticamente recriada ao ... + // reserva espaço em memória a primeira vez, e não recria ela ao chamar novamente + + printf (" Local Automatica = %i\n ", variavelLocalAutomatica); + printf (" Local Estática = %i\n ", variavelLocalEstatica); +} + +int +main () +{ + //draftfuction(); + //aula13(); + //aula14 (); + //aula16 (); + //exer2(); + //exerc3(); + /*while (1) + aula19(); */ + //resol16(); + //resol17(); + //resol18(); + //breakcode(); + //Christmans_tree(); + //cem_first(); + //tabela_ASCCI (); + //resolp11(); + /*neg(); + ASCII2(); + int x,i=5; + x=i++; + printf(" %d %d\n", i,x); + */ + aula30e31 (); + return 0; +} diff --git a/aulas.c~ b/aulas.c~ new file mode 100644 index 0000000..dda8766 --- /dev/null +++ b/aulas.c~ @@ -0,0 +1,414 @@ +#include +/*int fatorial(int n) +{ + fatorial(n) = n*fatorial (n-1); + fatorial (1)=1; + ou + fatorial n = for (i=0;i<=n;i++); + +} +*/ +void neg() +{ + int z=20; + if(!z) + printf("Código de Z vale: %d\n",z); + } +int +draftfuction () +{ + int fatorial = 10; + int resposta = 1; + + for (; fatorial >= 1; --fatorial) + { + resposta *= fatorial; + //resposta = resposta * fatorial;5 * 4 * 3 *2 *1 + } + printf ("O numero fatorial e: %i\n", resposta); + return 0; + +} + +void +aula13 () +{ + int i = 0; + while (i != 0) + { + printf ("Teste\n"); + } + do + { + printf ("Teste do\n"); + } + while (i != 0); +} + +void +aula14 () +{ + /*int idade = 033; + int idd = 0x33; + printf("Favor informar idade:\n"); + + if (idade < 180) + + printf("A idd é:%i \te a do pai é:%d",idade,idd);//%Oi,%Oxi, + */ + int idade; + printf ("Informar idade\n"); + scanf ("%d", &idade); + + if (idade <= 5) + printf ("bebê\n"); + else if (idade > 5 && idade <= 10) + printf ("Criança\n"); + else if (idade > 10 && idade <= 18) + printf ("Adolescente\n"); + else if (idade > 18 && idade <= 50) + printf ("Adulto\n"); + else + printf ("idoso\n"); +} + +int +aula16 () +{ + /*int i; + + printf("Insira um nº inteiro de 1 a 5\n"); */ + return 0; +} + +void +exer2 () +{ + int first, second; + puts ("Digite 2 numbers.."); + scanf ("%i%d", &first, &second); + if (second == 0) + puts ("Divisão por 0 nao permitido"); + else + { + if (first % second == 0) + { + puts ("é divisível"); + printf ("E o quociente de %i por %d é:%d \n", first, second, + first / second); + } + else + puts ("not divisible"); + } +} + +void +exerc3 () // ter em conta numero Pos e Neg.. numero !0 que é qdo para +{ + int num, inverted, div = 1; + scanf ("%d", &num); + inverted = num % 10; + num /= 10; + while (num != 0) + { + inverted *= 10; + div *= 10; + inverted += num % 10; + num /= 10; + } + printf ("O número digitado é %i\n", inverted); +} + +void +aula19 () +{ + /*const */ int variavelInt = 10; + printf ("%i\n", variavelInt); + scanf ("%i", &variavelInt); + printf ("%d\n", variavelInt); + + double varD = -10.10; + printf ("%f\n", varD); + scanf ("%lf", &varD); // ao ler temos de por o Quantifier... + printf ("%f\n", varD); + +} + +void +resol16 () +{ + int i, n; + scanf ("%d", &n); + for (i = 1; i <= n; i++) // como 0 nâo aparece, então temos de ser nos a fazer o programa... + printf ("%d %d\n", i, n - i + 1); +} +//*() +void +resol17 () +{ + int i, j, n; + char ch; + + printf ("Introd. um Nº: "); + scanf ("%d", &n); + printf ("Introd. um Char: "); + scanf (" %c", &ch); + + for (i = 1; i <= n; i++) + { + for (j = 1; j <= n; j++) + putchar (ch); + putchar ('\n'); + } +} + +void +resol18 () +{ + int num, multipl, i; + puts ("Digite um num.."); + scanf ("%d", &num); + puts ("____________"); + multipl = num / 10; + for (i = num; i < (multipl + 1) * 10; i++) + { + if (i % 3 == 0) + continue; + else + printf ("%i\n", i); + + } + putchar ('\n'); +} + +void +breakcode () +{ + int n = 33; + /* conclusion-> aulas.c:166:2: error: break statement not within loop or switch + break; + ^ + break; */ + printf ("easy pizi%i", n); +} + +void +Christmans_tree () +{ + int ramos, i, j, contador; + puts ("Digite o numero de ramos que pretende para a sua arvore"); + scanf ("%d", &ramos); + for (i = 0, contador = 0; i <= ramos; i++) // se puser i=1 não executa 1 ciclo (o dentro not satisfaz a condição) inultimente, que deixa somente 1a linha em branco + { + contador += i; + for (j = 1; j <= i; j++) + { + putchar ('*'); + + } + puts (""); // or putchar('\n'); + } + printf ("O numero de asteriscos (*) é: %d\n", contador); +} + +/* +void piramide_alfabética() +{ + int letra=65,i,j,contador; + char converte; + puts("Digite o numero de ramos que pretende para a sua arvore"); + scanf("%d",&ramos); + for (i=0,contador = 0;i<=ramos;i++) + { contador += i; + letra++; + for (j=1;j<=i;j++) + { + converte = (char) letra; + getchar(""); + putchar('',); + + } + puts(""); + } + printf("O numero de letras (*) é: %d\n",contador); +} +*/ +void +cem_first () +{ + int valor = 0; + while (valor > 100 || valor < 1) // boa cena como é que não me lembrei disto antes... utilizar o ciclo do ... while + scanf ("%d", &valor); +} + +/*int ASCIItable () +{ + int i,jan=20; + for(i=0;i<256;i++) + while (jan>0) + { + jan--; + printf("%3d --> %c\n", i,(char) i); + continue; + } + getchar('c' || 'C'); + return 0; +} + +#include */ +int +tabela_ASCCI () +{ + int i = 0; //,j=20; + char ch; // o por o J como carga init... + for (i = 1; i < 256; i++) + { + printf ("%d --> %c\n", i, (char) i); + if (i % 20 == 0) //(j>0) + { + scanf (" %c", &ch); + switch (ch) + { + case 'c':break; //continue; + default:puts ("Pressione c ou C, para continuar"); + + } + /* else + { + scanf(" %c",&ch); + switch(ch) + { + case 'c': break;//continue; + default: {puts ("Go out");break;} + } + } */ + //j--; + + } + } +return 0; +} + + + +int +resolp11 () +{ + int i, conta; + char ch; + for (conta = 1, i = 0; i <= 255; i = i + 1) + { + printf ("%3d --> %c\n", i, (char) i); + if (conta == 20) + { + do + { + puts ("Pressione c ou C para continuar ..."); + scanf (" %c", &ch); // para no ciclo seguinte não mandar, a mensagem pela tecla enter... + } + while (ch != 'c' && ch != 'C'); + conta = 1; + } + else + conta++; + } + return 0; +} + +int ASCII2() +{ + int n1,n2,Max,Min,i; + puts("DIgite os limites do intervalo!"); + scanf("%d%i",&n1,&n2); + if ( n1 > n2) + { + Max=n1; + Min=n2; + } + else + { + Max=n2; + Min=n1; + } + i=Min; + do + { + printf(" %3d --> %c\n", i, (char) i); + i++; + } + while(i<=Max); // for <= + return 0; +} +/* +int ASCII2Damas() +{ + int Max,min,tmp,i; + puts//("Digite os valores que pretende apresentar com limites... comece no min e depois o max\n\n//( Introd. dois Nºs: "); + scanf (" %d",&Max); scanf("%d",&min); + while( nmin<0 || nmin // outra função para este tipo de ciclo... + if (Max < min) + { + tmp= Max; + Max=min; desta forma é mais fácil to DO as trocas de valores de var's + min=tmp; + } + for(i=min;i<=Max;i++) // ou ++i + printf(" %3d --> %c\n", i, (char) i); + //printf(" Os valores corretos da variáveis necessários são: " + */ + + +void aula30e31() +{ + void teste(void); // desnecessário , bastava por o protótipo em cima + teste(); + teste(); + teste(); + //invalid space not recognized printf (" O valor associado é %d", variavelLocalEstatica); + + //return 0; +} +// acesso à função variável vísivel a todas a minha funções, o modo é utilizar uma variável global ... Fora dos colchetes +int gVariavelGlobal = 2; +void teste(void) +{ + int variavelLocalAutomatica = 2; // é recriada.. qualquer valor que tenha antes é perdido (sempre que a chamam) + variavelLocalAutomatica *= 2; + static int variavelLocalEstatica = 2; //Não perde o Valor e não fará esta Atribuição/Assignment + variavelLocalEstatica *= 2; // o valor aproveita os valores calculados em chamadas anteriores a esta função! + // differences a estática não perde o valor dela quando é chamada + // logo não é automáticamente recriada ao ... + // reserva espaço em memória a primeira vez, e não recria ela ao chamar novamente + + printf(" Local Automatica = %i\n ", variavelLocalAutomatica); + printf(" Local Estática = %i\n ", variavelLocalEstatica); +} + +int +main () +{ + //draftfuction(); + //aula13(); + //aula14 (); + //aula16 (); + //exer2(); + //exerc3(); + /*while (1) + aula19(); */ + //resol16(); + //resol17(); + //resol18(); + //breakcode(); + //Christmans_tree(); + //cem_first(); + //tabela_ASCCI (); + //resolp11(); + /*neg(); + ASCII2(); + int x,i=5; + x=i++; + printf(" %d %d\n", i,x); + */ + aula30e31(); + return 0; +} diff --git a/aulas.o b/aulas.o new file mode 100644 index 0000000..5fb9092 Binary files /dev/null and b/aulas.o differ diff --git a/aulas30para_cima.c b/aulas30para_cima.c new file mode 100644 index 0000000..8520213 --- /dev/null +++ b/aulas30para_cima.c @@ -0,0 +1,11 @@ +#import +//aula 36 +int main(void) +{ + int vetor[10] = {6,4,1,9,8,7,0,5,7,3}; + int i; + void ordemCrescente(int vetor[]); // 1-vetor (nome) 2- tamanho (nº inteiro dos membros que existem..) + return 0; +} +// criar uma função que ordene os vetores... uma variável que lê estes elementos.. + diff --git a/bookmarks.html b/bookmarks.html new file mode 100644 index 0000000..3790551 --- /dev/null +++ b/bookmarks.html @@ -0,0 +1,61 @@ + + + +Bookmarks +

Bookmarks Menu

+ +

+

Recently Bookmarked +
Recent Tags +
+

Ubuntu and Free Software links

+
Information and resources about Ubuntu, Debian and Free Software in general +

+

Ubuntu +
Ubuntu Wiki (community-edited website) +
Make a Support Request to the Ubuntu Community +
Debian (Ubuntu is based on Debian) +
Ubuntu One - The personal cloud that brings your digital life together +

+

Mozilla Firefox

+

+

Help and Tutorials +
Customize Firefox +
Get Involved +
About Us +

+

Bookmarks Toolbar

+
Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar +

+

Most Visited +
Tempo em Mirandela - Previsão para 14 dias +
Getting Started +

ip

+

+

c - warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’ - Stack Overflow +

+

+

Unsorted Bookmarks

+

+

Fernando Silva - Teaching +
Your description goes here +
Configuring sound in Linux | TechRepublic +
Configuring sound in Linux can be a real hassle if you don't know the tools. One sound configuration tool that's been around for quite some time is sn +
TechRepublic - A Resource for IT Professionals +
TechRepublic helps IT decision-makers identify technologies and strategies to empower workers and streamline business processes. The site delivers a unique blend of original content by IT professionals, peer-to-peer advice from the largest community of IT leaders on the Web, and a vast library of professional resources from the leading vendors in the IT industry. TechRepublic features blogs, community forums, vendor white papers, software downloads, Webcasts, and research. +
Como encadernar um livro em casa - YouTube +
Passo a passo de uma encadernação de livro caseira utilizando cola quente +
Microsoft TechNet Home Page +
TechNet is the home for all resources and tools designed to help IT professionals succeed with Microsoft products and technologies. +
Jogada do Mês +
Notícias do Jogada do Mes +
Centro de Informática - FCUP +
Favoritus Bookmarks Online +
Favoritus Bookmarks Online +
SASUP - Pavilhão Luís Falcão +
Festas Universitárias Porto +
Encontra facilmente a hora, local, line up e preço das melhoras festas universitárias do Porto. E muito mais... Live your life! +

+

diff --git a/bool b/bool new file mode 100644 index 0000000..fdc100f Binary files /dev/null and b/bool differ diff --git a/boolean b/boolean new file mode 100644 index 0000000..0cb1328 Binary files /dev/null and b/boolean differ diff --git a/boolean.c b/boolean.c new file mode 100644 index 0000000..f43166d --- /dev/null +++ b/boolean.c @@ -0,0 +1,13 @@ +#include +#include  +int main() +{ + int i=9-1; + int c; + while (i) + printf("\n%d",--i); + c=getchar(); + printf("O carater proveniente da função é:%d e \t%c\v",c,(char) c); + bool variavelBool=true; + return printf("%i\n",variavelBool); +} diff --git a/bye.c b/bye.c new file mode 100644 index 0000000..097b636 --- /dev/null +++ b/bye.c @@ -0,0 +1,6 @@ +#include +int bye() +{ +puts ("bye"); +return 0; +} diff --git a/c01p01 b/c01p01 new file mode 100644 index 0000000..944aee7 Binary files /dev/null and b/c01p01 differ diff --git a/c01p01.c b/c01p01.c new file mode 100644 index 0000000..f84998f --- /dev/null +++ b/c01p01.c @@ -0,0 +1 @@ +main (){} diff --git a/c01p01.c~ b/c01p01.c~ new file mode 100644 index 0000000..976c7aa --- /dev/null +++ b/c01p01.c~ @@ -0,0 +1,3 @@ +main () +{ +} diff --git a/c01p02 b/c01p02 new file mode 100644 index 0000000..9efe3d3 Binary files /dev/null and b/c01p02 differ diff --git a/c01p02.c b/c01p02.c new file mode 100644 index 0000000..45b49fd --- /dev/null +++ b/c01p02.c @@ -0,0 +1,7 @@ +#include + +main () +{int x=39 , y =32; +printf ("He%%llo \a" ); printf("\n"); +scanf("%d %d",&x,&y); +printf("W\borl\n\bd");} /* estar \7 ou \a e igual e resultam em 1 sinal sonoro independete do numero*/ diff --git a/c02e017 b/c02e017 new file mode 100644 index 0000000..e7608c0 Binary files /dev/null and b/c02e017 differ diff --git a/c02e017.c b/c02e017.c new file mode 100644 index 0000000..ea7dc85 --- /dev/null +++ b/c02e017.c @@ -0,0 +1,13 @@ +#include +main () +{int a,b; + printf ("Defina os seus dois inteiros para efectuar as operações\n"); +scanf("%d""%d",&a,&b); +printf("A soma das constantes é: %d+%d=%d\n",b,a,a+b); + printf(" Da subtração a-b resulta: %d-%d=%d\n",a,b,a-b); +printf("Da subtração resulta: %d-%d=%d\n",b,a,b-a); +printf(" Da \"subtração\" -b +a resulta : %d-%d=%d\n",b,a,-b+a); +printf("Da multiplicação resulta: %d*%d=%d\n",b,a,b*a); +printf("o quociente é: %d: ou / %d=%d\n",b,a,b/a); +printf("Do resto resulta: %d%%%d=%d\n",b,a,b%a); +} diff --git a/c02e017ASPAS b/c02e017ASPAS new file mode 100644 index 0000000..0ea8736 Binary files /dev/null and b/c02e017ASPAS differ diff --git a/c02e018 b/c02e018 new file mode 100644 index 0000000..aef7b00 Binary files /dev/null and b/c02e018 differ diff --git a/c02e018.c b/c02e018.c new file mode 100644 index 0000000..0b209c5 --- /dev/null +++ b/c02e018.c @@ -0,0 +1,9 @@ +#include +main() { + int tempo;/*ou do tipo float*/ + printf("Introduz o numero de segundos em questão\n"); + scanf("%d",&tempo); + printf("o tempo decorrido em horas: %d\v", (tempo/60)/60); + printf("o tempo decorrido em minutos %d \n",tempo/60); + printf("conversão a segundos dá: %d \b\v",tempo); +} diff --git a/c02e018R b/c02e018R new file mode 100644 index 0000000..d43d94e Binary files /dev/null and b/c02e018R differ diff --git a/c02e018R.c b/c02e018R.c new file mode 100644 index 0000000..1fa6362 --- /dev/null +++ b/c02e018R.c @@ -0,0 +1,11 @@ +#include +main(){ +long int n_segundos; +printf("informação de escrever o numero\b ;\n") +scanf("%ld",&n_segundos); +printf("o numeros de horas:%ld\voi\n",n_segundos/(60*60)); +printf("na parte do minutos é %ld\r\v\r",(n_segundos%3600)/60);/*1hora=60min*/ +printf("os sobrantes segundos:%ld\n",n_segundos%60); + +printf("O tempo com todos os parametros é:%ldhoras %ldminutos e %ldsegundos",n_segundos/(60*60),(n_segundos%3600)/60,(n_segundos%60)%60); +} diff --git a/c02e019 b/c02e019 new file mode 100644 index 0000000..1447e94 Binary files /dev/null and b/c02e019 differ diff --git a/c02e019.c b/c02e019.c new file mode 100644 index 0000000..9485b10 --- /dev/null +++ b/c02e019.c @@ -0,0 +1,10 @@ +#include +main() { + float n; + printf("escolha o seu real \voi\bhuashuash\n\b\bboi"); + scanf("%f",&n); + printf(" a parte inteira do n é %d\n",(int) n); + printf("a parte decimal do numero é igual %f\n",n-(int) n); + /* ou n-((int) n) ou real*/ + } + diff --git a/c02e03 b/c02e03 new file mode 100644 index 0000000..10a42fb Binary files /dev/null and b/c02e03 differ diff --git a/c02e03.c b/c02e03.c new file mode 100644 index 0000000..49afa1a --- /dev/null +++ b/c02e03.c @@ -0,0 +1,9 @@ +#include +main() +{ +int n1,n2; +float n3; +printf("Introduza 2 Nºs:\n"); +scanf("%d%f",&n1,&n3); +printf("o número surgido foi %f\n",n1+n3); +} diff --git a/c02e04 b/c02e04 new file mode 100644 index 0000000..be64dbf Binary files /dev/null and b/c02e04 differ diff --git a/c02e04.c b/c02e04.c new file mode 100644 index 0000000..403c84a --- /dev/null +++ b/c02e04.c @@ -0,0 +1,5 @@ +#include +main() +{ +printf("O Tamanho de um inteiro = %ld bits\n", sizeof(int)*8); +} diff --git a/c02e05.c b/c02e05.c new file mode 100644 index 0000000..ee22bb5 --- /dev/null +++ b/c02e05.c @@ -0,0 +1,11 @@ +#include +main() +{ +printf("O Tamanho de um char = %d Bytes\n", sizeof(char)); + +printf("O Tamanho \"em Bytes*8\" de um inteiro = %ld bits\n", sizeof(int)*8); + +printf("O Tamanho em Bytes de um inteiro = %ld bits\n", sizeof(int)*8); +printf("O Tamanho em Bits de um float = %ld \n", sizeof(float)*8); +printf("O Tamanho em Bytes de um double = %ld \n", sizeof(double) +} diff --git a/c02e16 b/c02e16 new file mode 100644 index 0000000..1a9378b Binary files /dev/null and b/c02e16 differ diff --git a/c02e16.c b/c02e16.c new file mode 100644 index 0000000..d53308d --- /dev/null +++ b/c02e16.c @@ -0,0 +1,7 @@ +#include /*Má implementação*/ +main() +{ char ch1 = 'd',ch2 = 'K';/* o valor inicializado não interfere nos print's do programa*/ + printf("Introduza um Inteiro:\t "); + scanf("%d",&ch2); + printf("O valor de ch1 = '%c' e ch2 ='%c'\n",ch1,ch2); +} diff --git a/c02eo4 b/c02eo4 new file mode 100644 index 0000000..fdb7e65 Binary files /dev/null and b/c02eo4 differ diff --git a/c02p013 b/c02p013 new file mode 100644 index 0000000..b997a4b Binary files /dev/null and b/c02p013 differ diff --git a/c02p013.c b/c02p013.c new file mode 100644 index 0000000..03b17cd --- /dev/null +++ b/c02p013.c @@ -0,0 +1,10 @@ +#include +main() { +char ch1,ch2; +printf("\tIntroduza um carater\n"); +scanf("%c",&ch1); +printf("Introduza um 2ºcarater\n"); +fflush(stdin); +scanf(" %c",&ch2); +printf("Os carateres associados as variáveis são: %c e %c\n",ch1,ch2); +} diff --git a/c02p014 b/c02p014 new file mode 100644 index 0000000..1da1f39 Binary files /dev/null and b/c02p014 differ diff --git a/c02p12 b/c02p12 new file mode 100644 index 0000000..97d43a6 Binary files /dev/null and b/c02p12 differ diff --git a/c02p12.c b/c02p12.c new file mode 100644 index 0000000..697a225 --- /dev/null +++ b/c02p12.c @@ -0,0 +1,9 @@ +#include +main() { +char ch1,ch2; +printf("\tIntroduza um carater\n"); +scanf("%c",&ch1); +printf("Introduza um 2ºcarater\n"); +scanf("%c",&ch2); +printf("Os carateres associados as variáveis são: %c e %c\n",ch1,ch2); +} diff --git a/c1e3 b/c1e3 new file mode 100644 index 0000000..1417d47 Binary files /dev/null and b/c1e3 differ diff --git a/c1e3.c b/c1e3.c new file mode 100644 index 0000000..b18ee81 --- /dev/null +++ b/c1e3.c @@ -0,0 +1,6 @@ +#include + +int main(int argc, char *argv[]) + printf("Hello!\n"); + return 12; // código de terminação / ver no terminal com: echo $? COLOQUEI o numero -677 91 +} diff --git a/c1e3.c~ b/c1e3.c~ new file mode 100644 index 0000000..18211c6 --- /dev/null +++ b/c1e3.c~ @@ -0,0 +1,6 @@ +#include + +int main() { + printf("Hello!\n"); + return 12; // código de terminação / ver no terminal com: echo $? +} diff --git a/c1e4b b/c1e4b new file mode 100644 index 0000000..176df63 Binary files /dev/null and b/c1e4b differ diff --git a/c1e4b.c b/c1e4b.c new file mode 100644 index 0000000..b6e1c5f --- /dev/null +++ b/c1e4b.c @@ -0,0 +1,20 @@ +#include +#include + +int main(int argc, char* argv[]) { // parâmetros na linha de chamada do terminal + int k, nr; + + if (argc != 3) { // se nr. errado de parâmetros + printf("Usage: %s \n", argv[0]); + return 1; + } + nr = atoi(argv[2]); // converter para int + if (nr <= 0) { // valor de inválido + printf("The nr of times should be greater than 0!\n"); + return 2; + } + for (k=0; k vezes + printf("Hello %s!\n", argv[1]); + return 0; +} + diff --git a/c1e4b.c~ b/c1e4b.c~ new file mode 100644 index 0000000..b6e1c5f --- /dev/null +++ b/c1e4b.c~ @@ -0,0 +1,20 @@ +#include +#include + +int main(int argc, char* argv[]) { // parâmetros na linha de chamada do terminal + int k, nr; + + if (argc != 3) { // se nr. errado de parâmetros + printf("Usage: %s \n", argv[0]); + return 1; + } + nr = atoi(argv[2]); // converter para int + if (nr <= 0) { // valor de inválido + printf("The nr of times should be greater than 0!\n"); + return 2; + } + for (k=0; k vezes + printf("Hello %s!\n", argv[1]); + return 0; +} + diff --git a/c1e5b b/c1e5b new file mode 100644 index 0000000..b0016ad Binary files /dev/null and b/c1e5b differ diff --git a/c1e5b.c b/c1e5b.c new file mode 100644 index 0000000..a047c30 --- /dev/null +++ b/c1e5b.c @@ -0,0 +1,17 @@ +#include +#include + +int main(int argc, char* argv[], char* envp[]) { // acesso a variáveis de ambiente + int k=0; + char name[100]; + + if (argc != 1) { // invocar sem parâmetros + printf("Usage: %s\n", argv[0]); + return 1; + } + while (strncmp("USER=", envp[k], 5)!=0) // descobrir a linha que começa por "USER=" + k++; + strcpy(name, &envp[k][5]); // extrair o resto da linha + printf("Hello %s!\n", name); + return 0; +} diff --git a/cap6e5.c b/cap6e5.c new file mode 100644 index 0000000..faf8190 --- /dev/null +++ b/cap6e5.c @@ -0,0 +1,19 @@ +#import + + +char * memcpy(char *dest, char *orig, int n) +{ + for (int i=0; i < n; i++) + (*dest[i]) = (*orig[i]); + return dest; +} + +int main() +{ + +int vet1={'a','g','f','t','y','t','h','o','I'}; +int vet2[10]; +memcpy(vet1,vet2,4); +memcpy(vet2,vet1,7); + +} diff --git a/dica.xcf b/dica.xcf new file mode 100644 index 0000000..9eadd60 Binary files /dev/null and b/dica.xcf differ diff --git a/exercio6.c b/exercio6.c new file mode 100644 index 0000000..bb71db0 --- /dev/null +++ b/exercio6.c @@ -0,0 +1,29 @@ +// PROGRAMA p6a.c +#include +#define BUF_LENGTH 256 +int main(void) +{ + FILE *src, *dst; + char buf[buf_length]; + if ( ( src = fopen( "infile.txt", "r" ) ) == NULL ) + { + exit(1) + } + if ( ( dst = fopen( "outfile.txt", "w" ) ) == NULL ) + { + exit(2) + } +Sistemas +Operativos +– +MIEIC +Jorge +Silva + while( ( fgets( buf, MAX, src ) ) != NULL ) + { + fputs( buf, dst ); + } + fclose( src ); + fclose( dst ); + exit(0); // zero é geralmente indicativo de "sucesso" +} diff --git a/exercio6.c~ b/exercio6.c~ new file mode 100644 index 0000000..bb71db0 --- /dev/null +++ b/exercio6.c~ @@ -0,0 +1,29 @@ +// PROGRAMA p6a.c +#include +#define BUF_LENGTH 256 +int main(void) +{ + FILE *src, *dst; + char buf[buf_length]; + if ( ( src = fopen( "infile.txt", "r" ) ) == NULL ) + { + exit(1) + } + if ( ( dst = fopen( "outfile.txt", "w" ) ) == NULL ) + { + exit(2) + } +Sistemas +Operativos +– +MIEIC +Jorge +Silva + while( ( fgets( buf, MAX, src ) ) != NULL ) + { + fputs( buf, dst ); + } + fclose( src ); + fclose( dst ); + exit(0); // zero é geralmente indicativo de "sucesso" +} diff --git a/ficheiros b/ficheiros new file mode 100644 index 0000000..6698552 Binary files /dev/null and b/ficheiros differ diff --git a/ficheiros.c b/ficheiros.c new file mode 100644 index 0000000..3307325 --- /dev/null +++ b/ficheiros.c @@ -0,0 +1,29 @@ +#import //dif. entre #include + +int gVariavelGlobal = 2 +;// recomenda pois ela acedido por todas as funções logo...: + fácil de identificar em programas grandes etc + +int main (void){ + + void teste(void); // só pode ser usada no main.. normalmente é a declaração é pública assim fica protected??? + +printf("Global = %i\n", gVariavelGlobal); + teste(); + teste(); + + return 0; +} + +void teste(void){ + int varLocalAuto = 2; + varLocalAuto *= 2; + + static int variavelLocalEstatica = 2; + variavelLocalEstatica *= 2; + + gVariavelGlobal *= 2; + + printf("Local Automatica = %i\n", varLocalAuto ); + printf("Local Estática = %i\n", variavelLocalEstatica ); + printf("Global = %i\n", gVariavelGlobal); // a local age como se fosse estatica +} diff --git a/fprintf&scanf.c b/fprintf&scanf.c new file mode 100644 index 0000000..6c9239f --- /dev/null +++ b/fprintf&scanf.c @@ -0,0 +1,27 @@ +#include +#include +int main() +{ + FILE *p; + char str[80],c; + /* Le um nome para o arquivo a ser aberto: */ + printf("\n\n Entre com um nome para o arquivo:\n"); + scanf("%s", str); /* não se usa a função gets() e sim scanf dessa forma */ + if (!(p = fopen(str,"w"))) /* Caso ocorra algum erro na abertura do arquivo..*/ + { /* o programa aborta automaticamente */ + printf("Erro! Impossivel abrir o arquivo!\n"); + exit(1); + } + /* Se nao houve erro, imprime no arquivo, fecha ...*/ + fprintf(p,"Este e um arquivo chamado(com ou sem caminho e formato):\n%s\n", str); + fclose(p); + /* abre novamente para a leitura */ + p = fopen(str,"r"); + while (!feof(p)) + { + fscanf(p,"%c",&c); + printf("%c",c); + } + fclose(p); + return(0); +} diff --git a/fps b/fps new file mode 100644 index 0000000..54ee2f3 Binary files /dev/null and b/fps differ diff --git a/fputs b/fputs new file mode 100644 index 0000000..3579f2b Binary files /dev/null and b/fputs differ diff --git a/fputs.c b/fputs.c new file mode 100644 index 0000000..a1431d6 --- /dev/null +++ b/fputs.c @@ -0,0 +1,16 @@ +#include +#include +#include +int main() +{ +FILE *fp; + +fp = fopen("arquivos/fputs.txt", "w+"); // subscreve, passa por cima!! + +fputs("Esta é a programação c.", fp); +fputs("Esta é uma linguagem de programação do sistema.", fp); + +fclose(fp); + +return(0); +} diff --git a/freadEx b/freadEx new file mode 100644 index 0000000..2525edd Binary files /dev/null and b/freadEx differ diff --git a/freadEx.c b/freadEx.c new file mode 100644 index 0000000..cd99ab9 --- /dev/null +++ b/freadEx.c @@ -0,0 +1,33 @@ +/* fread example: read an entire file */ +#include +#include + +int main () { + FILE * pFile; + long lSize; + char * buffer; + size_t result; + + pFile = fopen ( "myfile.bin" , "rb" ); + if (pFile==NULL) {fputs ("File error",stderr); exit (1);} + + // obtain file size: + fseek (pFile , 0 , SEEK_END); + lSize = ftell (pFile); + rewind (pFile); + + // allocate memory to contain the whole file: + buffer = (char*) malloc (sizeof(char)*lSize); + if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} + + // copy the file into the buffer: + result = fread (buffer,1,lSize,pFile); + if (result != lSize) {fputs ("Reading error",stderr); exit (3);} + + /* the whole file is now loaded in the memory buffer. */ + + // terminate + fclose (pFile); + free (buffer); + return 0; +} diff --git a/freadTR b/freadTR new file mode 100644 index 0000000..fbd5b3d Binary files /dev/null and b/freadTR differ diff --git a/freadTR.c b/freadTR.c new file mode 100644 index 0000000..f7457c0 --- /dev/null +++ b/freadTR.c @@ -0,0 +1,19 @@ +#include +#include + +int main() +{ +// Declaramos um ponteiro(link para o endereço da memória) para o arquivo de nome: 'pf' +FILE *pf; +char conteudo[100]; + +pf = fopen("arquivos/texto.txt", "rb"); /* Abre o arquivo novamente para leitura */ + +fread(&conteudo, sizeof(char), 100,pf); /* Le em conteudo o valor da variável armazenada anteriormente pf */ + +printf("\nO conteúdo do arquivo é':\n %s \n", conteudo); + +fclose(pf); + +return(0); +} diff --git a/fwriteTR b/fwriteTR new file mode 100644 index 0000000..43e741b Binary files /dev/null and b/fwriteTR differ diff --git a/fwriteTR.c b/fwriteTR.c new file mode 100644 index 0000000..5fdaad1 --- /dev/null +++ b/fwriteTR.c @@ -0,0 +1,26 @@ +#include +#include +int main() +{ +FILE *pf; +int NUM = 88; +int pilido; +if((pf = fopen("arquivos/arquivo.bin", "wb")) == NULL) /* Abre arquivo binário para escrita */ +{ +printf("Erro na abertura do arquivo"); +exit(1); +} +if(fwrite(&NUM, sizeof(int), 1,pf) != 1) /* Escreve a variável NUM | o operador sizeof, que retorna o tamanho em bytes da variável ou do tipo de dados. */ +printf("Erro na escrita do arquivo"); +fclose(pf); /* Fecha o arquivo */ +if((pf = fopen("arquivos/arquivo.bin", "rb")) == NULL) /* Abre o arquivo novamente para leitura */ +{ +printf("Erro na abertura do arquivo"); +exit(1); +} +if(fread(&pilido, sizeof(int), 1,pf) != 1) /* Le em pilido o valor da variável armazenada anteriormente */ +printf("Erro na leitura do arquivo"); +printf("\nO valor de NUM, lido do arquivo e': %d \n\n", pilido); +fclose(pf); +return(0); +} diff --git a/p2b.c b/p2b.c new file mode 100644 index 0000000..70eae14 --- /dev/null +++ b/p2b.c @@ -0,0 +1 @@ +#include diff --git a/relogio.c b/relogio.c new file mode 100644 index 0000000..9a0b34c --- /dev/null +++ b/relogio.c @@ -0,0 +1,9 @@ +#include +clock_t times(struct tms *buf); +struct tms { +clock_t tms_utime; /* tempo de CPU gasto em código do processo */ +clock_t tms_stime; /* tempo de CPU gasto em código do sistema chamado pelo processo */ +clock_t tms_cutime; /* tempo de CPU dos filhos (código próprio) */ +clock_t tms_cstime; /* tempo de CPU dos filhos (cód. do sistema) * + +ticks_seg = sysconf(_SC_CLK_TCK); diff --git a/relogio.c~ b/relogio.c~ new file mode 100644 index 0000000..42f52dc --- /dev/null +++ b/relogio.c~ @@ -0,0 +1,7 @@ +#include +clock_t times(struct tms *buf); +struct tms { +clock_t tms_utime; /* tempo de CPU gasto em código do processo */ +clock_t tms_stime; /* tempo de CPU gasto em código do sistema chamado pelo processo */ +clock_t tms_cutime; /* tempo de CPU dos filhos (código próprio) */ +clock_t tms_cstime; /* tempo de CPU dos filhos (cód. do sistema) * diff --git a/removeTR b/removeTR new file mode 100644 index 0000000..e8131f1 Binary files /dev/null and b/removeTR differ diff --git a/removeTR.c b/removeTR.c new file mode 100644 index 0000000..94dae6e --- /dev/null +++ b/removeTR.c @@ -0,0 +1,13 @@ +#include +#include +#include +int main() +{ + /* 0(zero) é verdadeiro(true), e 1(um) é falso(false), em C usa-se números! */ + if(remove("arquivos/Faded") == 0){ + printf("Arquivo removido com sucesso!\n"); + }else{ + printf("Não removido, talvez não exista.\n"); + } +return(0); +} diff --git a/retorno b/retorno new file mode 100644 index 0000000..5717222 Binary files /dev/null and b/retorno differ diff --git a/retorno.c b/retorno.c new file mode 100644 index 0000000..84c5551 --- /dev/null +++ b/retorno.c @@ -0,0 +1,11 @@ +/* 3a) Valor de retorno de um programa + * 23/02/2016 + * Manuel Curral + */ + +#include +int main() +{ + puts("Olá World, estou na 1@ aula de SOPE :))))"); + return 99.1; +} diff --git "a/revis\303\265es/ex1" "b/revis\303\265es/ex1" new file mode 100644 index 0000000..430fe85 Binary files /dev/null and "b/revis\303\265es/ex1" differ diff --git "a/revis\303\265es/ex1.c" "b/revis\303\265es/ex1.c" new file mode 100644 index 0000000..b99253b --- /dev/null +++ "b/revis\303\265es/ex1.c" @@ -0,0 +1,39 @@ + +// Arrays & C‐Strings +// ex_00.c +// A program that reads the evolution of a person's weight +// during some months of a year +// JAS + +#include + +#define MAX_NAME_LENGTH 50 // avoid "magic numbers" +#define NUM_MONTHS 12 + +int main() +{ +char name[MAX_NAME_LENGTH]; +int weight[NUM_MONTHS]; +int i; + +printf("Name ? "); +scanf("%s", name); // try with "Lou Costello" :‐) + +for (i = 0; i < NUM_MONTHS; i++) +{ +printf("weight[%d] ? ", i + 1); +scanf("%d", &weight[i]); +} + +for (i = 0; i < NUM_MONTHS; i++) +{ +printf("weight[%d] = %d\n", i + 1, weight[i]); +} + +// TO BE DONE ...??? complete the data processing + +return 0; +} + + + diff --git a/sstream.cpp b/sstream.cpp new file mode 100644 index 0000000..4bdfe15 --- /dev/null +++ b/sstream.cpp @@ -0,0 +1,18 @@ +#include // std::string +#include // std::cout +#include // std::stringstream, std::stringbuf +#include +using namespace std; +int main () { + string nome = "Nuno Cr"; + int idd = 20; + std::stringstream ss; + ss << nome << " , " << idd; + s string = ss.str(); + /* + ss.str ("Example string"); + std::string s = ss.str(); + */ + std::cout << s << '\n'; + return 0; +} diff --git a/untitled b/untitled new file mode 100644 index 0000000..7d43e29 --- /dev/null +++ b/untitled @@ -0,0 +1,35 @@ +//Pipes e FIFO's 3 Exemplo Pipe entre pai e filho: +#include +#include +#include +#include +#define MAXLINE 128 +int main(void) +{ +int +n, fd[2]; +pid_t +pid; +char +line[MAXLINE]; +pipe(fd); +pid = fork( ); +if (pid > 0) { +/* pai */ +close(fd[0]); +/* fecha lado receptor do pipe */ +write(fd[1], "hello world +\ +n", 12); +close(fd[1]); +} +else { +/* filho */ +close(fd[1]); +/* fecha lado emissor do pipe */ +n = read(fd[0], line, MAXLINE); +write(STDOUT_FILENO, line, n); +close(fd[0]); +} +return 0; +}