2011-03-01 243 views
-2

我有一個文本文件。我必須從文本文件中讀取一個字符串。我正在使用c代碼。任何身體可以幫助嗎?從文件中讀取字符串

+1

您應該嘗試努力尋找解決方案,而不是隻是在此發佈期望別人爲您完成工作。此外,讓你的問題更清楚。 – 2011-03-01 12:45:06

回答

2

這應該工作,它會讀取一整行(這不是很清楚你所說的「字符串」的意思):

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

int read_line(FILE *in, char *buffer, size_t max) 
{ 
    return fgets(buffer, max, in) == buffer; 
} 

int main(void) 
{ 
    FILE *in; 
    if((in = fopen("foo.txt", "rt")) != NULL) 
    { 
    char line[256]; 

    if(read_line(in, line, sizeof line)) 
     printf("read '%s' OK", line); 
    else 
     printf("read error\n"); 
    fclose(in); 
    } 
    return EXIT_SUCCESS; 
} 

返回值是1,如果所有的錯誤順利,0。

由於這使用了普通的fgets(),它將在行尾保留'\ n'換行符(如果存在)。

+0

這裏我想從文件中讀取特定的字符串。 – user556761 2011-03-01 11:15:01

+3

你沒有在問題中說過。 – Stewart 2011-03-01 11:16:59

+2

@ user556761在這裏,您想接受人們對衆多問題的回答,提出更清晰的問題,並自行做一些工作。 – 2011-03-01 12:10:55

15

使用fgetsC中的文件讀取字符串。

喜歡的東西:避免爲了簡便

#include <stdio.h> 

#define BUZZ_SIZE 1024 

int main(int argc, char **argv) 
{ 
    char buff[BUZZ_SIZE]; 
    FILE *f = fopen("f.txt", "r"); 
    fgets(buff, BUZZ_SIZE, f); 
    printf("String read: %s\n", buff); 
    fclose(f); 
    return 0; 
} 

安全檢查。

2
void read_file(char string[60]) 
{ 
    FILE *fp; 
    char filename[20]; 
    printf("File to open: \n", &filename); 
    gets(filename); 
    fp = fopen(filename, "r"); /* open file for input */ 

    if (fp) /* If no error occurred while opening file */ 
    {   /* input the data from the file. */ 
    fgets(string, 60, fp); /* read the name from the file */ 
    string[strlen(string)] = '\0'; 
    printf("The name read from the file is %s.\n", string); 
    } 
    else   /* If error occurred, display message. */ 
    { 
    printf("An error occurred while opening the file.\n"); 
    } 
    fclose(fp); /* close the input file */ 
}