我打印一個函數可以從文件中得到特定的行,如string = extract_line(2),那麼字符串將是文件的第二行的內容。 但是當我試圖把該函數放在頭文件中時,我得到了Segmentation錯誤。C編程:從函數返回字符串
這裏是我的代碼: test.c的:
#include "extract_line.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
extract_line(2);
extract_line(3);
printf("%s\n", str);
return 0;
}
extract_line.h
#include <stdio.h>
#include <stdlib.h>
#define TEMP_PATH "/home/pi/project/PCD_8544_screen/show_on_LCD/network_speed.txt"
static char str[256];
void extract_line(int Tgt_Line)
{
FILE *fp;
fp=fopen(TEMP_PATH, "r");
// char str[256];
char holder;
int line=0;
while((holder=fgetc(fp)) != EOF) {
if(holder == '\n') line++;
if(line == Tgt_Line) break; /* 1 because count start from 0,you know */
}
if(holder == EOF) {
printf("%s doesn't have the 2nd line\n", fp);
//error:there's no a 2nd
}
int i=0;
while((holder=fgetc(fp)) != EOF && (holder != '\n')) {
// putchar(holder);
str[i] = holder;
i++;
}
// printf("%s\n",str);
fclose(fp);
// return str;
}
@seb我會在稍後添加它,但這不是主要問題。 –
當然是!我希望如何保證我沒有它就能複製你的行爲?也許你的文件丟失了!停止行事愚蠢。 – Sebivor
對不起,我只是C語言的新手。 –