1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
typedef struct{
char **matriz;
} Dado;
void ler_agumento (Dado *dado, int argc, char **argv){
int opcao;
dado -> matriz = NULL;
while (opcao = getopt (argc,argv, "e::") != -1){
switch (opcao){
case 'e':
dado->matriz = optarg;
break;
}
}
}
void imprimir (FILE *file){
char *line = (char*) malloc(sizeof(char));
if(file == NULL) {
fprintf(stderr, "Erro ao abrir o arquivo.txt.");
}
while(fgets(line, 80, file) != NULL) {
printf("%s", line);
}
}
int main(int argc, char **argv[]){
int i;
Dado dado;
dado.matriz = malloc(sizeof(char *)*8);
for(i=0; i<8; i++){
dado.matriz[i] = malloc(8);
}
ler_argumento (&dado, argc, argv);
FILE *file = fopen(dado.matriz,"r");
imprimir (file);
fclose (file);
return 0;
}
I want to print the content that is inside a file. I passed as argument through the terminal opening like this (./executar -e arquivo.txt
). The output it generates is the error message from printf()
showing that the file is empty and then shows segmenttion fault.
Here: malloc(sizeof(char)) you are allocating space for a single character. Maybe it should be: malloc(80*sizeof(char)). The array to contain the string".txt file" should be at least 12 and not 8.
– anonimo
Good evening! I made this modification but the exit continued the same.
– Nascimento
You do
dado->matriz = optarg;
butchar** matriz
andchar* optarg
are uncompromising.argv
should bechar** argv
orchar* argv[]
– user72726
Thanks for the tips. I made the changes leaving char *matrix and char **argv. The output continues in the same way
– Nascimento