6

I have one text file. I have to read one string from the text file. I am using c code. can any body help ?

2
  • 3
    You should really try and put some effort in searching for a solution rather than just posting it here expecting others to do the job for you. Also, make your question clearer. Commented Mar 1, 2011 at 12:45
  • Possible duplicate of Read string from file in C Commented Jun 6, 2018 at 1:02

4 Answers 4

20

Use fgets to read string from files in C.

Something like:

#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; } 

Security checks avoided for simplicity.

Sign up to request clarification or add additional context in comments.

Comments

5

This should work, it will read a whole line (it's not quite clear what you mean by "string"):

#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; } 

The return value is 1 if all went well, 0 on error.

Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).

2 Comments

You didn't say that in the question.
@user556761 Here you want to accept people's answers to your numerous questions, ask clearer questions, and do a little work of your own.
5
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 */ } 

1 Comment

A terminating null character is automatically appended after the characters copied to string. So you don't have to do string[strlen(string)] = '\0';
4

This is a Simple way to get the string from file.

#include<stdio.h> #include<stdlib.h> #define SIZE 2048 int main(){ char read_el[SIZE]; FILE *fp=fopen("Sample.txt", "r"); if(fp == NULL){ printf("File Opening Error!!"); } while (fgets(read_el, SIZE, fp) != NULL) printf(" %s ", read_el); fclose(fp); return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.