A
al3x4nder
Hi All,
I want read file to array of strings
and found the next soluition:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define LINESIZE 1024
#define SIZE(length) (sizeof(char) * length + 1)
#define BUFFSIZE 1024
int main(int argc, char **argv){
int cnt, i;
FILE *fp;
char *p, *buff[BUFFSIZE];
if(argc < 2){
printf("Error: I need filename as argument!\n");
return 1;
}
if((fp = fopen(argv[1], "r")) == NULL){
printf("Error: %s\n", strerror(errno));
return 1;
}
/* Read file into array buff[] */
for(cnt = 0; cnt < BUFFSIZE; cnt++){
p = (char *)malloc(SIZE(LINESIZE));
if (fgets(p, LINESIZE, fp) == NULL) {
free(p);
break;
}
buff[cnt] = p;
}
/* Do something with readed data */
for(i = 0; i < cnt; i++){
printf("%s",buff);
}
return 0;
}
I`m a newbie in C, and now question:
may be exist a better way?
Thanks, and sorry for my English.
I want read file to array of strings
and found the next soluition:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define LINESIZE 1024
#define SIZE(length) (sizeof(char) * length + 1)
#define BUFFSIZE 1024
int main(int argc, char **argv){
int cnt, i;
FILE *fp;
char *p, *buff[BUFFSIZE];
if(argc < 2){
printf("Error: I need filename as argument!\n");
return 1;
}
if((fp = fopen(argv[1], "r")) == NULL){
printf("Error: %s\n", strerror(errno));
return 1;
}
/* Read file into array buff[] */
for(cnt = 0; cnt < BUFFSIZE; cnt++){
p = (char *)malloc(SIZE(LINESIZE));
if (fgets(p, LINESIZE, fp) == NULL) {
free(p);
break;
}
buff[cnt] = p;
}
/* Do something with readed data */
for(i = 0; i < cnt; i++){
printf("%s",buff);
}
return 0;
}
I`m a newbie in C, and now question:
may be exist a better way?
Thanks, and sorry for my English.