reading a string from a file - c

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

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.

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).

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 */
}

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

Related

Trying to read first line of file using fgets

I'm trying to write a program that will read the first line of a txt file and output it. I can't get the fgets to display in my fprintf statement when running the program.
#include "example.h"
// function: main
int main(int argc, const char** argv) {
//declare filepointer
FILE *fp;
//declare variables
char c[10];
long size;
//open file
fp = fopen(argv[1], "r");
//first output read dimension of vector
fgets (c, 10, fp);
fprintf(stdout, "the dimension of the vector is %s\n", c);
fclose(fp);
return 0;
}
The text file has the following contents:
4
45.0
62.0
55.6
8.2
But my output is just reading as:
the dimension of the vector is
You always need to be careful of what the user is going to enter as input in the program. To do this, as mentioned in the comment, we should always check if the fopen(), fgets(), and the arguments are correctly passed before taking them into use.
Let's try the following code:
#include <stdio.h>
#define EXIT_FAILURE 1
#define MAX_LEN 16
int main(int argc, char *argv[]) {
FILE *fp = NULL;
char c[MAX_LEN];
if (argc != 2) {
fprintf(stdout, "Usage: %s <file>\n", argv[0]);
return EXIT_FAILURE;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror(argv[1]);
fclose(fp); // Cleanup
return EXIT_FAILURE;
}
if (fgets(c, sizeof(c), fp) == NULL) {
fprintf(stderr, "File read error.\n");
fclose(fp); // Cleanup
return EXIT_FAILURE;
}
fclose(fp);
fprintf(stdout, "The dimension of the vector is %s\n", c);
return 0;
}
In this case, I've got those same values as yours in the data.txt file.
The program outputs:
rohanbari#genesis:~/stack$ ./a.out data.txt
The dimension of the vector is 4

How can I write or append the content fo text file then display?

How can I write and create the file, append if the file exists, then display all string file text? I can't append the content to at the end of file text, then display all strings. Thank for reading!
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char** argv) {
char c, filename[100], content[100];
FILE *fptr;
printf("File name: ");
scanf("%s", filename);
printf("Enter content: ");
gets(content);
if ((fptr = fopen(filename, "r")) == NULL)
{
fptr = fopen(fptr, "w");
fprintf(fptr,"%s", content);
}
else{
fptr = fopen(fptr, "a");
fprintf(fptr,"%s", content);
}
c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}
If you want to open a file for reading and to also append to it, you can do that with just one call to fopen by using the mode a+.
fptr = fopen(filename, "a+");
if (fptr == NULL)
{
// Handle not being able to open the file
}
If the file doesn't exist, it will create it. The position for reading will be at the beginning of the file, but anything you write to it will be at the end.
There are lot of bugs as mentioned by others in comments. I tried to explain in comments, read it carefully.
int main(int argc, char** argv) {
char filename[100], content[100];
FILE *fptr;
printf("Enter content: \n");
fgets(content,sizeof(content),stdin); /*use fgets() instead of gets()*/
printf("File name: ");
scanf("%s", filename);
if ((fptr = fopen(filename, "r")) == NULL) {/*if doesn't exist */
fptr = fopen(filename, "w"); /*create it */
fprintf(fptr,"%s", content); /* and write it */
}
else{
/* it should be a+ if you want to read, as you are doing using fgetc() */
fptr = fopen(filename, "a+");/*if exist, write at end of file */
fprintf(fptr,"%s", content);/* write at end */
}
rewind(fptr);/* move the fptr to beginning to read further */
int c = 0; /* fgetc() returns integer */
while( (c = fgetc(fptr))!= EOF) {
printf ("%c\n", c);
}
fclose(fptr);
return 0;
}
Use fgets() instead of gets(). Read here Why is the gets function so dangerous that it should not be used?

C. Can't open a text file with fopen on Windows Vista

I wanted to learn how to use getc function in C so I wrote a little program that is supposed to give the first letter of a text file as an output.
Here's how it looks:
int main()
{
int character;
FILE *file;
file = fopen("file.txt", "r");
if(file == NULL)
printf("can't open\n");
character = getc(file);
printf("%c", character);
fclose(file);
return 0;
}
It fails to open the file.txt file and I can't figure out why. file.txt is in the same folder as my program's .exe file. I'm using Windows Vista.
Thanks in advance
This extracts the program's location from argv[0]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MYFILE "plik.txt"
int main(int argc, char *argv[]) {
char fname[_MAX_PATH+1];
int znak;
FILE *plik;
char *ptr;
strcpy(fname, argv[0]);
ptr = strrchr(fname, '\\');
if(ptr == NULL) {
strcpy(fname, MYFILE);
}
else {
strcpy(ptr+1, MYFILE);
}
plik = fopen(fname, "r");
if(plik == NULL) {
printf("Can't open %s\n", fname);
}
else {
znak = getc(plik);
printf("First char of %s is %c\n", fname, znak);
fclose(plik);
}
getchar();
return 0;
}
Try
if (plik == NULL) { perror("plik.txt"); exit(EXIT_FAILURE); }
for a better understanding of the cause of error.

Better way to convert string to integer

I wrote this code to read a variable in a .txt file, ignore the first character and convert into a integer.It works but looks dumb, is there a better way to do this? I'm using just one string here but it's supposed to work with four.
void read(char a[])
{
int i;
char a1[3];
for (i = 0; i<3; ++i){
a1[i]= a[i+1];
}
int b1 = atoi(a1);
}
int main()
{
FILE *file;
file = fopen( "file.txt", "r");
if (file == NULL) {
printf( "Arquivo nao encontrado\n");
}
char a[4];
fscanf(file, "%s\n",&a);
read(a);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char filename[] = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return(EXIT_FAILURE);
}
int value;
if (fscanf(fp, "%*c%d", &value) != 1)
{
fprintf(stderr, "Failed to read integer value from file %s\n", filename);
fclose(fp);
return EXIT_FAILURE;
}
printf("Read %d\n", value);
fclose(fp);
return 0;
}
The %*c reads a single character but does not assign it. The * to suppress an assignment is a general mechanism in the scanf()
family of functions.
Untested code.

Reading line by line from a file in C

What I am trying to do is print out the contents of a file line by line. I run the program in terminal by doing: ./test testText.txt. When I do this, random characters are printed out but not what is in the file. The text file is located in the same folder as the makefile. What's wrong?
#include <stdio.h>
FILE *fp;
int main(int argc, char *argv[])
{
char line[15];
fp = fopen(*argv, "r");
while((fgets(line, 15, fp)) != NULL)
{
printf(line);
printf("\n");
}
}
When I do this, random characters are printed out but not what is in the file
These characters are not random, and in fact they are coming from a file. It's not the file that you are trying to read, though - it's the executable file which you are running.
*argv represents the name of the executable; add this line to see what's in *argv:
printf("%s\n", *argv);
The actual command line arguments start at argv[1], so you need
fp = fopen(argv[1], "r");
The first argument passed on the command line is at argv[1], while *argv refers to argv[0]. argv[0] contains the filename of the executable - you are printing out the content of the executable.
The following code prints out the entire argv[] array, then reads your file and prints it.
#include <stdio.h>
int main( int argc, char *argv[] )
{
for( int i = 0; i < argc; i++ )
{
printf( "argv[%d] : %s\n", i, argv[i] ) ;
}
if( argc >= 2 )
{
FILE* fp = fopen( argv[1], "r" ) ;
if( fp != NULL )
{
char line[15];
while( fgets( line, sizeof(line), fp ) != NULL )
{
printf( "%s", line ) ;
}
}
}
return 0 ;
}
Note that fgets() will read an entire line including the , so there is no need to print '\n', especially because with only 15 characters, your line buffer may well not contain an entire line. Note also the tighter localisation of variables - your code needlessly made fp global.
Other refinements are the safe use of the array size rather than literal 15, and the use of a literal constant string for the format specifier. You should avoid passing a variable string for the printf() format string - if your input itself contains format specifiers, printf() will try to read data from arguments that do not exist with undefined results.
Q: What's wrong?
A humble critique:
#include <stdio.h>
FILE *fp; // Perhaps this should be declared inside main?
int main(int argc, char *argv[])
{
char line[15]; // Are the file lines all 14 characters or less? (seems small)
fp = fopen(*argv, "r"); // Opening the binary executable file (argv[0])? Intereting.
// Should check here to ensure that fopen() succeeded.
while((fgets(line, 15, fp)) != NULL)
OK... well, remember that this isn't a text file.. it's an executable (due to *argv). This will read some wacky (but not random) characters from the executable.
{
printf(line); // Bad practice. Should be: printf("%s", line);
Ok... now print the wacky characters?
printf("\n"); // Redundant. The '\n' characters will be supplied in 'line'.
}
// fclose() call missing.
// Integer return value for main() is missing.
}
Here is (perhaps) what was actually intended:
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int rCode = 0;
FILE *fp = NULL;
char line[255+1];
if(argc != 2)
{
printf("Usage: %s {filepath}\n", *argv);
goto CLEANUP;
}
errno=0;
fp = fopen(argv[1], "r");
if(NULL == fp)
{
rCode=errno;
fprintf(stderr, "fopen() failed. errno:%d\n", rCode);
goto CLEANUP;
}
while(fgets(line, sizeof(line), fp)) /* --As per 'chux' comment */
printf("%s", line);
CLEANUP:
if(fp)
fclose(fp);
return(rCode);
}
Or, if the intent is truly to print the content of the executable, perhaps this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int rCode = 0;
FILE *fp = NULL;
off_t offset = 0;
errno=0;
fp = fopen(*argv, "r");
if(NULL == fp)
{
rCode=errno;
fprintf(stderr, "fopen() failed. errno:%d\n", rCode);
goto CLEANUP;
}
for(;;)
{
char line[16];
size_t bytesRead;
int index;
char ascii[16+1];
memset(ascii, 0, sizeof(ascii));
bytesRead = fread(line, 1, sizeof(line), fp);
if(0==bytesRead)
break;
printf(" %08zX | ", offset);
for(index=0; index < bytesRead; ++index)
{
printf("%02hhX%c", line[index], 7==index ? '-' : ' ');
ascii[index] = isprint(line[index]) ? line[index] : '.';
}
printf("%*s %s\n", (16 -index) * 3, "", ascii);
offset += bytesRead;
}
if(errno)
{
rCode=errno;
fprintf(stderr, "fgets() failed. errno:%d\n", errno);
}
CLEANUP:
if(fp)
fclose(fp);
return(rCode);
}
your file name found at index 1 of argv.
if (argc <= 1) {
printf("no file was given\n");
exit(-1);
}
// open file from argv[1]
// ...

Resources