I am currently trying to do my own shell, and it has to be polyglot. So I tryed to implement a function that reads the lines in a .txt file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char lang[16] = {'t','r','y'};
char aMsg[512];
// functions
void takeFile() {
int i =0;
char namFil[32];
char lg[16];
FILE * file;
char tmp[255];
char * line = tmp;
size_t len = 0;
ssize_t read;
strcpy(namFil,"/media/sf_Projet_C/");
strcpy(lg,lang);
strcat(lg, ".txt");
strcat(namFil, lg);
file = fopen(namFil, "r");
printf("%s\n", namFil);
while((read = getline(&line,&len, file)) != -1) {
aMsg[i] = *line;
i++;
}
}
enum nMsg {HI, QUIT};
int main(void) {
takeFile();
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
}
I am on win7 but I compile with gcc on a VM.
I have a warning saying :
format'%s' expects argument of type 'char *', but argument 2 (and 3) has type 'int' [-Wformat=]
I tried to execute the prog with %d instead of %s and it prints numbers.
I don't understand what converts my aMsg into a int.
My try.txt file is just :
Hi
Quit
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT])
-->printf("%s\n%s\n", &aMsg[HI], &aMsg[QUIT])
BTW I don't know if this instruction does what you want. – LPsprintf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
doesn't look right. Maybe you wantprintf("%s\n%s\n", &aMsg[HI], &aMsg[QUIT]);
? And don'tfree(line);
as you haven'tmalloc
ed it. – SpikatrixNULL terminated string
starting fromindex 0
ofaMsg
array and aNULL terminated string
starting fromindex 1
ofaMsg
array. Probably you wantchar *aMsg[512];
changing your code according to array of pointers. – LPs