- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to Count number of lines present in the file
In the Go programming language, a file is a named resource for storing data that can be read from or written to. It provides a way for the program to persist data, even after the program has finished executing. Here in this article we will discuss different methods using which we can count the number of lines in a file.
Method 1: Using a user-defined function
In this method, we will write a go language program to count the number of lines present in the file by using bufio, fmt and os packages.
Algorithm
Step 1 − First, we need to import the fmt, bufio and os packages.
Step 2 − Now, start the main function. Inside the main() create a new file and store it in a variable.
Step 3 − if any error occurs during this process then store it in a variable called err and print it on the screen.
Step 4 − Now in order to write into this file use NewWriter() function present in bufio package and use another function WriteString() to enter string values to the file.
Step 5 − Now, open the file by using Open() function and use scan() function to read the data present inside the file.
Step 6 − Again use for loop to iterate over the data present inside the file and increment the count variable every time a new line is fetched.
Step 7 − Once the iteration gets completed the count variable contains the number of lines present in that particular file.
Step 8 − At last we need to print this result on the screen by using fmt.Println() function.
Example 1
In the following example, we are going to count the number of lines present in the file using user-defined function
package main import ( "bufio" "fmt" "os" ) func main() { // creating a new file file, err := os.Create("newFile.txt") if err != nil { fmt.Println(err) return } defer file.Close() // writing data in the file writer := bufio.NewWriter(file) _, err = writer.WriteString("Hello, World!\n this is the first line\n followed by the second line\n and the third one") if err != nil { fmt.Println(err) return } err = writer.Flush() if err != nil { fmt.Println(err) return } // fetching the file file, err = os.Open("newFile.txt") if err != nil { fmt.Println(err) return } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) // getting the number of lines var count int for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { fmt.Println(err) return } fmt.Println("Number of lines in file:", count) }
Output
Number of lines in file: 4
Method 2: By Using Internal Functions
In this method, we will write a go language program to count the number of lines present in a file by using internal inbuilt library functions.
Syntax
func len(v Type) int
The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.
func Split(str, sep string) []string
Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.
Algorithm
Step 1 − First, we need to import the required packages.
Step 2 − Now, start the main function. Inside the main() create a new file and store it in a variable.
Step 3 − Now in order to write into this file use function WriteString() and enter string values to the file.
Step 4 − Now, open the file by using ReadFile() function present in ioutil package to read the data present inside the file.
Step 5 − Use split() function to count the number of lines and print them on the screen.
Example 1
In this example, we are going to learn about how to use an internal function like writestring () to count number of lines present in the file
package main import ( "bufio" "fmt" "io/ioutil" "os" "strings" ) func main() { // creating a new file file, err := os.Create("newFile.txt") if err != nil { fmt.Println(err) return } defer file.Close() // writing data in the file writer := bufio.NewWriter(file) _, err = writer.WriteString("Hello, World!\n this is the first line\n followed by the second line\n and the third one\n and a new one") if err != nil { fmt.Println(err) return } err = writer.Flush() if err != nil { fmt.Println(err) return } // fetching the file data, err := ioutil.ReadFile("newFile.txt") if err != nil { panic(err) } lines := strings.Split(string(data), "\n") fmt.Printf("Number of lines: %d\n", len(lines)) }
Output
Number of lines: 5
Example 2
In this example, we have used the ReadLine() inbuilt library function present in reader package in order to write a go language program to count the number of lines in a given file.
package main import ( "bufio" "fmt" "os" ) func main() { // creating a new file file, err := os.Create("newFile.txt") if err != nil { fmt.Println(err) return } defer file.Close() // writing data in the file writer := bufio.NewWriter(file) _, err = writer.WriteString("Hello, World!\n this is the first line\n followed by the second line\n and the third one\n and a new one") if err != nil { fmt.Println(err) return } err = writer.Flush() if err != nil { fmt.Println(err) return } file, err = os.Open("newFile.txt") if err != nil { panic(err) } defer file.Close() reader := bufio.NewReader(file) lineCount := 0 for { _, _, err := reader.ReadLine() if err != nil { break } lineCount++ } fmt.Printf("Number of lines: %d\n", lineCount) }
Output
Number of lines: 5
Conclusion
In the first example, we have used a use-defined function, where as in the second method, we have used two example for internal function to count the number of lines present in a file
- Related Articles
- C# Program to count the number of lines in a file
- C Program to count the number of lines in a file?
- C program to count characters, lines and number of words in a file
- How to count the total number of lines in the file in PowerShell?
- How to count the number of lines in a text file using Java?
- Golang Program to Count the Number of Digits in a Number
- Python program to count number of substring present in string
- Golang Program to count the number of nodes in a linked list.
- Golang Program to Count number of leaf nodes in a tree
- Golang Program to Count Trailing Zeros in Factorial of a Number
- Golang program to count the number of nodes in a doubly linked list.
- Golang program to count number of nodes in a circular linked list
- Write a C program to find total number of lines in an existing file
- Count lines in a file using Linux bash
- Golang Program to count the number of flips to convert a given integer to another.
