1

Есть функция main() в ней вызывается функция file(file_name) с адресом на файла, который нужно прочитать в массив и вернуть в переменную в main (Сижу в ubuntu 13.10 пишу в NetBeans 7.4)

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <stdlib.h> 
#include <string.h>

char *file(const char *config_file) {

    FILE *fp = fopen(config_file, "r");
    char line[1024];
    char *ip_address[1024] = {};
    char ch = getc(fp);
    int index = 0;
    int i = 0, i2 = 0;
    while (ch != EOF) {
        if (ch != '\n') {
            line[index++] = ch;
        } else {
            line[index] = '\0';
            index = 0;
            ip_address[i] = malloc(strlen(line) * sizeof (char));
            strcpy(ip_address[i], line);
            i++;
        }
        ch = getc(fp);
    }
    fclose(fp);
    return ip_address;
}
int main(int argc, char *argv[]) {
    int opt = 0, i;
    char *in_fname = NULL;
    char count = 0;
    while ((opt = getopt(argc, argv, "f:")) != -1) {
        switch (opt) {
            case 'f':
                in_fname = optarg;
                char *buff = file(in_fname);
                for (count = 0; count < 12; count++) {
                    printf("%s", buff[count]);
                }
        case '?':
            if (optopt == 'f') {
                printf("Вы не выбрали файл\n");
            }
            break;
        }
    }
    return 0;
}

Запускать пытаюсь так

./app -f 'text.txt'

Содержимое файла text.txt просто строки через "\n", но в main() я хочу получать их без "\n"

1 ответ 1

1

@Negash, во первых, возвращать надо не char * а char ** (аналогично параметру argv[] в main),

во вторых, память под возвращаемый массив указателей надо тоже выделять malloc-ом,

а в третьих, читать строки и урезать '\n' IMHO удобней так

char **ip_address = malloc(sizeof(*ip_address) * (LIMIT + 1));
char str[LINE_MAX];

while (i < LIMIT && fgets(str, sizeof(str), infile)) {
   int l = strlen(str);
   str[l > 0 ? l - 1 : l] = 0;
   ip_address[i++] = strdup(str);
}
ip_address[i] = 0; // так можно будет узнать размер этого массива
... места мало...

UPD

Решил преобразовать в ответ и немного дополнить. В Линуке (GNU) есть хорошая функция -- getline(). С ней функция чтения строк становится получше.

avp@avp-xub11:~/hashcode$ ./a.out filelines.c
test get_filelines(filelines.c)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define START_INCR 64
#define LIMIT_INCR 1024

char **
get_filelines (const char *filename)
{
  FILE *in = filename ? fopen(filename, "r") : stdin;
  if (!in) // can't open (see errno)
    return 0;
  char **res = 0, *str = 0;
  size_t rsx = 0, capacity = 0, incr = START_INCR, strsz, i;
  ssize_t lstr;

  while ((lstr = getline(&str, &strsz, in)) >= 0) {
    if (rsx + 2 > capacity) { 
      // increase res[] if need it
      if (!(res = (typeof(res))realloc(res, (capacity += incr) * sizeof(*res))))
        return 0; // no memory (see errno)
      if ((incr <<= 1) > LIMIT_INCR)
        incr = LIMIT_INCR;
    }
    if (lstr)
      str[lstr - 1] = 0; // del '\n'
    res[rsx++] = str;
    str = 0;
  }

  if (in != stdin)
    fclose(in);
  if (res) { 
    res[rsx++] = 0; // terminate lines list by NULL
    res = (char **)realloc(res, rsx * sizeof(*res));
  } else {
    errno = 0; // empty file
  }

  return res;
}

int
main (int ac, char *av[])
{
  printf ("test get_filelines(%s)\n", av[1] ? av[1] : "stdin");
  char **flines = get_filelines(av[1]);

  if (!flines)
    perror("get_filelines");
  else 
    while (*flines) 
      puts(*flines++);

  return !flines;
}
avp@avp-xub11:~/hashcode$

Это она файл со своим кодом печатает.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.