2011-03-01 187 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 */ 
}