创建一个指针数组并将每一行转换为字符串?

时间:2015-03-01 20:18:18

标签: c arrays pointers buffer

所以我得到一个.lst文件,我需要读取它并将内容存储到缓冲区,然后将信息存储在带行号的.txt中。但是,我需要使用指向cbuf指针的指针,并使用函数get_lines和read_file。我有一个总线错误,我认为它在get_lines,但我不确定。 代码:

#include <stdlib.h>
#include <stdio.h>

int readfile(FILE *fp, char **cbuf); //mallocs a char buffer and reads a file into it, returns count of chars
char **get_lines(char *cbuf, int bufsize); //mallocs an array of pointers to lines in cbuf, returns array's address

int main(int argc, char *argv[])           //reads a list-file into a buffer, generates a pointer array to lines/strings
{
  int i,bufsize;
  char *cbuf;
  char **lines;
  FILE *fp;

  if( (fp=fopen(argv[1],"r")) == NULL)
    {
      perror("ERROR: bad/no filename");
      exit(0);
    }
  bufsize= readfile(fp,&cbuf);       //create a buffer for the file, read the file into the buffer
   lines= get_lines(cbuf, bufsize) ;  //create an array of pointers to lines in the file, convert each line to a string
  i=0;
  while( lines[i] != NULL) {         //last entry in lines[] holds a NULL to mark end of data
printf("%i\t%s\n",i,lines[i]); //display line/strings pointed to by entries in lines

i++;
}
  return 0;
}

int readfile(FILE *fp,char**cbuf)
{
  int i;
  char c;

  fseek(fp, 0L, SEEK_END);
  int bufsize = ftell(fp);
  fseek(fp, 0L, SEEK_SET);

  *cbuf = (char *)malloc(sizeof(char) * bufsize);

  for (i = 0; i < bufsize; i++)
    {
      c = fgetc(fp);
      (*cbuf)[i] = c;
    }
  return bufsize;
}

char **get_lines(char *cbuf, int bufsize)
{
  char **lines;
  int i,j;

  lines[0] = &(cbuf[0]);

  j = 0;
  for (i = 0; i < bufsize; i++)
    {
      if (cbuf[i] == '\n')
        {
          cbuf[i] = '\0';
          lines[j++] = &cbuf[i] + j;
        }
      lines[bufsize] = NULL;
    }
  return lines;
}

1 个答案:

答案 0 :(得分:0)

在输出之前,你真的必须将整个文件存储在内存中吗?这可以通过循环读取每个char并写入输出来完成。最终它会写入文本文件。

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    int linenum = 1, c, pending = 1;
    FILE *fp;
    FILE *fo = stdout;

    if (argc < 2)                           // check argc
        {
        perror("ERROR: no argument");
        exit(0);
        }
    if ((fp=fopen(argv[1],"rt")) == NULL)   // added text mode
        {
        perror("ERROR: bad filename");
        exit(0);
        }
    while ((c = fgetc(fp)) != EOF) {
        if (pending) {                      // start a new line
            fprintf (fo,"%04d\t", linenum++);
            pending = 0;
        }
        putc(c, fo);
        if (c == '\n')                      // check end of line
            pending = 1;
    }
    fclose(fp);
    return 0;
}