c++ - 函数返回char类型数组,调用 函数后如何接收值?
高洛峰
高洛峰 2017-04-17 15:24:13
0
3
783

我现在刚在学C语言,今天想要实现一个功能:

用C语言读取一个文件的指定行,(如读取a.log文件的3--5行),现在实现了读取函数, 但在main函数调用时不知道怎么接收返回的值。

代码如下:

#include <stdio.h>
/* 
读取a.log中第3行到第5行的内容 

*/

#define MAXLIN 100
#define FILENAME "a.log"
 

char* getFileRows(char* filename,int start_line, int end_line);


int main()
{  
    
    getFileRows(FILENAME,3,5);

  /*
  getFileRows 函数返回的是 data[3][100] 这种的char类型数组。
  getFileRows 函数返回的是char类型的数组, 我这里应该怎么定义变量,来接收返回值呢? 
  */
 
  
     

 return 1;    
}

/*
 读取文件, 读取 start_line 到 end_line 行之间的内容
*/
char* getFileRows(char* logfile,int start_line, int end_line)
{ 
    int k=0,i = 0 ; 
    int pos = 1;
    char c; 
    int line = end_line - start_line;
    char data[line][MAXLIN];
    FILE* fp = fopen(logfile,"r");
    
    if(fp == NULL){
         printf("FILE OPEN ERROR");
         getchar();
         exit(1);
    }  
    while(i<start_line && !feof(fp)){ 
       fseek(fp,pos,SEEK_SET);
       while( (c=fgetc(fp)) != NULL){
                   pos++; 
                   if(c == '\n'){ 
                    break;
                 } 
         } 
        i++;  
   } 
   
  for(k=0;k<=line;k++){
        fgets(data[k],MAXLIN,fp);   
  }   
   return data;   
}
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
黄舟

Do not directly return the array declared inside the function. The stack will be recycled after the function exits. Or just like you used fgets, define the buffer outside the function, and then pass the buffer and length as function parameters. Or you can malloc a piece of char memory inside the function, write the tail 0 internally, and then return this address, and free it externally after use. Of course, this is a bad programming habit. You can encapsulate a destroy function, After use, pass the returned address as a parameter and release all the memory requested in the get function.

阿神

Your data is on the stack, and the stack will be recycled when the function returns. Accessing the data will cause unpredictable errors.

Declare data in the main function, and then pass the data to getFileRows through parameters to receive the data.

洪涛

A data array should be declared outside the function, the array address and array length should be passed into the function as parameters, and the data should be read and saved inside the function (the array name is used as a pointer, and the array is no longer declared inside the function)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template