Предположим, у нас есть файл lista.txt
с таким содержанием:
John abc
Mark cdf
Susie hhh
как я могу получить первые слова каждой строки? (John
и Mark
и Susie
)?
Это мой код:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define BUF_DIM 1000
struct elem{
char nome[BUF_DIM];
};
int main()
{
int fileDescriptor;
int nread;
char carattere;
char nickname[BUF_DIM];
int i = 0, times = 0;
struct elem *top = NULL;
// Apertura del file in sola lettura
if( (fileDescriptor=open("lista.txt", O_RDONLY)) == -1 ){
perror("Errore con apertura del file");
exit(1);
}
// Lettura del file
while( read(fileDescriptor, &carattere, 1) == 1){ // un byte alla volta
if (carattere != ' ') {
times++;
//printf("%c\n", carattere);
nickname[i++] = carattere;
//printf("%c\n", nickname[i++])
}
else {
nickname[i++] = ' ';
}
}
nickname[times] = '\0';
printf("%s\n", nickname);
close(fileDescriptor);
return 0;
}