How to Read a File Line by Line or a Whole Text File At Once

How to read a file line by line or a whole text file at once?

You can use std::getline :

#include <fstream>
#include <string>

int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}

Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).

Further documentation about std::string::getline() can be read at CPP Reference.

Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}

Cloud Dataflow: reading entire text files rather than lines by line

I am going to give the most generally useful answer, even though there are special cases [1] where you might do something different.

I think what you want to do is to define a new subclass of FileBasedSource and use Read.from(<source>). Your source will also include a subclass of FileBasedReader; the source contains the configuration data and the reader actually does the reading.

I think a full description of the API is best left to the Javadoc, but I will highlight the key override points and how they relate to your needs:

  • FileBasedSource#isSplittable() you will want to override and return false. This will indicate that there is no intra-file splitting.
  • FileBasedSource#createForSubrangeOfFile(String, long, long) you will override to return a sub-source for just the file specified.
  • FileBasedSource#createSingleFileReader() you will override to produce a FileBasedReader for the current file (the method should assume it is already split to the level of a single file).

To implement the reader:

  • FileBasedReader#startReading(...) you will override to do nothing; the framework will already have opened the file for you, and it will close it.
  • FileBasedReader#readNextRecord() you will override to read the entire file as a single element.

[1] One example easy special case is when you actually have a small number of files, you can expand them prior to job submission, and they all take the same amount of time to process. Then you can just use Create.of(expand(<glob>)) followed by ParDo(<read a file>).

How can I read different lines of a text file with fgets?

So, how could I read the whole file

In order to read the whole file into a memory buffer, you could use the function fread. After turning the input into a string by appending a terminating null character, you could then use the function strstr to search the input for a certain word.

Here is a program which does this and searches the input for the word targetword:

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

int main( void )
{
FILE *fp;
char buffer[1000];
size_t read;

//open input file
fp = fopen( "input.txt", "rt" );
if ( fp == NULL )
{
fprintf( stderr, "ERROR: Unable to open input file!\n" );
exit( EXIT_FAILURE );
}

//read entire file into buffer
read = fread( buffer, 1, sizeof buffer, fp );

//verify that buffer was not too small
if ( read == sizeof buffer )
{
fprintf( stderr, "ERROR: Memory buffer is too small to contain entire input!\n" );
exit( EXIT_FAILURE );
}

//add terminating null character to make input a valid
//null-terminated string
buffer[read] = '\0';

//search input for target word
if ( strstr( buffer, "targetword" ) != NULL )
printf( "Found word!\n" );
else
printf( "Did not find word!\n" );

fclose( fp );
}

However, instead of reading the entire file at once (which could require a very large memory buffer), it is more common to read one line at a time in a loop, and in every loop iteration, you check whether the current line contains the word you are looking for. That way, the memory buffer only has to be large enough to store one line of input at once, instead of the entire input.

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

int main( void )
{
FILE *fp;
char line[100];
bool found = false;

//open input file
fp = fopen( "input.txt", "rt" );
if ( fp == NULL )
{
fprintf( stderr, "ERROR: Unable to open input file!\n" );
exit( EXIT_FAILURE );
}

//read one line per loop iteration
while ( fgets( line, sizeof line, fp ) != NULL )
{
//verify that line was not too long to fit into buffer
if ( strchr( line, '\n' ) == NULL )
{
fprintf( stderr, "line too long to fit buffer!\n" );
exit( EXIT_FAILURE );
}

//search for target word
if ( strstr( line, "targetword" ) != NULL )
{
found = true;
break;
}
}

if ( found )
printf( "Found word!\n" );
else
printf( "Did not find word!\n" );

fclose( fp );
}

However, both solutions have several possible issues:

  1. If the target word targetword is part of another word, for example thetargetword, then it will state that it found the target word. I'm not sure if this is what you want or if you want the target word to appear by itself.

  2. If the target word is syllabified so that, for example, target-\n appears in one line and word in the next line, then the program won't be able to find the word.

  3. The search is case-sensitive, so it will only find targetword, but not Targetword or TARGETWORD.

All of these issues can be solved, if necessary, but would require additional work.

How do you get python to read a whole text file, not just one line?

Your were breaking out of the loop:

(Btw i added a with statent for opening the file in a more pythonic way)

order = input("Please enter the name of the product you wish to purchase\n")
with open("barcode.txt","r") as myfile:
details=myfile.readlines() #reads the file and stores it as the variable 'details'
for line in details:
if order in line: #if the barcode is in the line it stores the line as 'productline'
productline=line
quantity=int(input("How much of the product do you wish to purchase?\n"))
itemsplit=productline.split(' ') #seperates into different words
price=float(itemsplit[1]) #the price is the second part of the line
total=(price)*(quantity) #this works out the price
print("Your total spent on this product is: " +'£'+str(total))

How to read a large file - line by line?

The correct, fully Pythonic way to read a file is the following:

with open(...) as f:
for line in f:
# Do something with 'line'

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.

There should be one -- and preferably only one -- obvious way to do it.



Related Topics



Leave a reply



Submit