You can simply check for the word in the while condition:
while (file >> word && word != "**********") {
hash(word);
}
You could also break
the loop when you reach the word (if you prefer how it looks).
while (file >> word) {
if (word == "**********") break;
hash(word);
}
Can also use an istream_iterator
such as
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
using namespace std;
int main()
{
ifstream file("prog7.dat");
istream_iterator<string> it(file);
while(*it != "**********")
hash(*it++);
}
When we reach the end of the file fgets() can’t read and returns NULL and the program will stop reading.,Open a file using the function fopen() and store the reference of the file in a FILE pointer.,Using feof() function check for end of file. since feof() returns true after it reaches the end.,Using feof():feof() function takes file pointer as argument and returns true if pointer reaches the end of the file.
Input File:
GeeksforGeeks | A computer science portal for geeks
The re module implements regular expressions by compiling a search pattern into a pattern object. Methods of this object can then be used to perform match operations.,The "rt" parameter in the open() function means "we're opening this file to read text data",Okay, how can we use Python to extract text from a text file?,Useful linksAbout Computer HopeSite MapForumContact UsHow to HelpTop 10 pages
On Linux, you can install Python 3 with your package manager. For instance, on Debian or Ubuntu, you can install it with the following command:
sudo apt - get update && sudo apt - get install python3
For macOS, the Python 3 installer can be downloaded from python.org, as linked above. If you are using the Homebrew package manager, it can also be installed by opening a terminal window (Applications → Utilities), and running this command:
brew install python3
Running Python with a file name will interpret that python program. For instance:
python3 program.py
A Python program can read a text file using the built-in open() function. For example, the Python 3 program below opens lorem.txt for reading in text mode, reads the contents into a string variable named contents, closes the file, and prints the data.
myfile = open("lorem.txt", "rt") # open lorem.txt for reading text contents = myfile.read() # read the entire file to string myfile.close() # close the file print(contents) # print string contents
If you save this program in a file called read.py, you can run it with the following command.
python3 read.py
With the for loop approach, the loop automatically stops when the end of the file is encountered. Or never even iterates once if the file is empty!,Write a program that: opens the file january06.txt reads in the header and ignores it uses a loop to read in all the rest of the lines one by one prints out only the day and the temperature from each line ,Important Note: If the condition becomes false during the body of the loop, the loop does not stop at that moment. The only time it decides whether to continue or stop is at the top of the loop on each iteration.,But what happens if you are at the end of the file when you call read or readline? You get the empty string. You then know you can stop trying to read more.
f = open('story.txt', 'r')
f
< _io.TextIOWrapper name = 'story.txt'
mode = 'r'
encoding = 'UTF-8' >
myfile = open('story.txt', 'r') s = myfile.readline() # Read a line into s. print(s) s # Notice the\ n that you only see when you look # at the contents of the variable.
Mary had a little lamb
'Mary had a little lamb\n'
s = myfile.readline() # The next call continues where we left off. print(s) s = myfile.readline() # And so on... print(s) myfile.close()
Python provides built-in functions and modules to support these operations.,The fileObj returned after the file is opened maintains a file pointer. It initially positions at the beginning of the file and advances whenever read/write operations are performed.,The fileinput module provides support for processing lines of input from one or more files given in the command-line arguments (sys.argv). For example, create the following script called "test_fileinput.py":,If you just want to read or write a file, use built-in function open().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_copy: Copy file line-by-line from source to destination
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: file_copy <src> <dest>
"""
import sys
import os
def main():
# Check and retrieve command-line arguments
if len(sys.argv) != 3:
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
fileIn = sys.argv[1]
fileOut = sys.argv[2]
# Verify source file
if not os.path.isfile(fileIn):
print("error: {} does not exist".format(fileIn))
sys.exit(1)
# Verify destination file
if os.path.isfile(fileOut):
print("{} exists. Override (y/n)?".format(fileOut))
reply = input().strip().lower()
if reply[0] != 'y':
sys.exit(1)
# Process the file line-by-line
with open(fileIn, 'r') as fpIn, open(fileOut, 'w') as fpOut:
lineNumber = 0
for line in fpIn:
lineNumber += 1
line = line.rstrip() # Strip trailing spaces and newline
fpOut.write("{}: {}\n".format(lineNumber, line))
# Need \n, which will be translated to platform-dependent newline
print("Number of lines: {}\n".format(lineNumber))
if __name__ == '__main__':
main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_list_oswalk.py - List files recursively from a given directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: files_list_oswalk.py [<dir>|.]
"""
import sys
import os
def main():
# Process command-line arguments
if len(sys.argv) > 2: # Command-line arguments are kept in a list 'sys.argv'
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
elif len(sys.argv) == 2:
dir = sys.argv[1] # directory given in command-line argument
else:
dir = '.' # default current directory
# Verify dir
if not os.path.isdir(dir):
print('error: {} does not exists'.format(dir))
sys.exit(1)
# Recursively walk thru from dir using os.walk()
for curr_dir, subdirs, files in os.walk(dir):
# os.walk() recursively walk thru the given "dir" and its sub-directories
# For each iteration:
# - curr_dir: current directory being walk thru, recursively from "dir"
# - subdirs: list of sub-directories in "curr_dir"
# - files: list of files/symlinks in "curr_dir"
print('D:', os.path.abspath(curr_dir)) # print currently walk dir
for subdir in sorted(subdirs): # print all subdirs under "curr_dir"
print('SD:', os.path.abspath(subdir))
for file in sorted(files): # print all files under "curr_dir"
print(os.path.join(os.path.abspath(curr_dir), file)) # full filename
if __name__ == '__main__':
main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_list_glob.py - List files recursively from a given directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: files_list [<dir>|.]
"""
import sys
import os
import glob # Python 3.5
def main():
# Process command-line arguments
if len(sys.argv) > 2: # Command-line arguments are kept in a list 'sys.argv'
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
elif len(sys.argv) == 2:
dir = sys.argv[1] # directory given in command-line argument
else:
dir = '.' # default current directory
# Check dir
if not os.path.isdir(dir):
print('error: {} does not exists'.format(dir))
sys.exit(1)
# List *.txt only
for file in glob.glob(dir + '/**/*.txt', recursive=True):
# ** match any files and zero or more directories and subdirectories
print(file)
print('----------------------------')
# List all files and subdirs
for file in glob.glob(dir + '/**', recursive=True):
# ** match any files and zero or more directories and subdirectories
if os.path.isdir(file):
print('D:', file)
else:
print(file)
if __name__ == '__main__':
main()
This is the simplest way to read a text file; it simply output the file content inside the terminal. Be careful: if the file is huge, it could take some time to complete the printing process! If you need to stop it, you can always press CTRL+C. Note that if you need to navigate through the document, you need to scroll the terminal output.,Once the file is opened, be careful! Don't start typing, or you will mess everything up! In fact, even if you can see the cursor, you have to press i to start typing and ESC after you finished typing. By the way, now I'm going to showing you some useful commands that concern reading (not writing):,An improved version of cat. If your file is longer than the display of the terminal, you can simply type,Once the document is open, you can type some commands to enable some useful features, such as:
This is the simplest way to read a text file; it simply output the file content inside the terminal. Be careful: if the file is huge, it could take some time to complete the printing process! If you need to stop it, you can always press CTRL+C
. Note that if you need to navigate through the document, you need to scroll the terminal output.
cat file_name.txt
An improved version of cat
. If your file is longer than the display of the terminal, you can simply type
more file_name.txt
This is the more
command with some enhancements, and is typically a better choice than cat
for reading medium to big documents. It opens file showing them from the beginning, allowing to scroll up/down/right/left using arrows.
less file_name.txt
The above command will show last 10 lines(default) of the file. To read last 3 lines, we need to write:
tail - 3 file_name.txt
There's another use case where this command is extremely useful. Imagine to have a empty document, that is filled while you are watching it; if you want to see new lines in real time while they are written to the file without reopening it, just open the file with the -f
option. It's really useful if you are watching some logs, for example.
tail - f file_name.txt
We can do this by simply providing the desired line number; the stream will read the text at that location.,Java supports several file-reading features. One such utility is reading a specific line in a file.,The readAllLines method returns a list of strings where each string is a line of text in the specified file. get(n) retrieves the string for the nthnthnth line.,In the code above, lines.skip is used to jump n lines from the start of the file. Just as before, the get() method returns a string.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class FileRead {
public static void main(String args[]) {
int n = 1; // The line number
try {
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
System.out.println(line);
} catch (IOException e) {
System.out.println(e);
}
}
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.*;
class FileRead {
public static void main( String args[] ) {
int n = 40; // The line number
String line;
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line = lines.skip(n).findFirst().get();
System.out.println(line);
}
catch(IOException e){
System.out.println(e);
}
}
}
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
class FileRead {
public static void main(String args[]) {
int n = 40; // The line number
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
for (int i = 0; i < n; i++)
br.readLine();
line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println(e);
}
}
}