Posts

Showing posts with the label File IO

In Cpp, Use vectors to compute students score

Image
#include <iostream> #include <fstream> #include <vector> #include <iomanip> using namespace std; bool read_in(vector<char> *store, char *path){ ifstream inf(path); if(inf){ char c; while(inf >> c){ store->push_back(c); } inf.close(); return true; } cout << "Error: Unable to load/read file: " << path << endl; return false; } int main(){ vector<char> answers; if(!read_in(&answers, (char*)"CorrectAnswers.txt")){ cin.get(); return 1; } vector<char> student; if(!read_in(&student, (char*)"StudentAnswers.txt")){ cin.get(); return 2; } if(answers.size() != student.size()){ cout << "Error: No. of questions & answers mismatch!" << endl; cin.get(); return 3; } int missed = 0, correct = 0; for(int i = answers.size()-1; 0 <= i; i --){ if(answers[i] != student[i]){ mi...

In Java, Count Program Execution Using Binary File I/O

Image
Download

In Cpp, Write Student Details To File And Read It Back

Image
Download

In Excel VBA, Reading Local Disk File

Image
Download

Write Algorithm To Update Score In Flat File.

Problem Statement: A file exists on the disk named students.dat. The file contains several records, and each record contains two fields: (1) the student’s name, and (2) the student’s score for the final exam. Design an algorithm that changes Julie Milan’s score to 100. Solution: Start Declare InFile As File Declare OutFile As File Declare Name As String Declare Score As Integer Set InFile = "students.dat" Set OutFile = "students.tmp" For Each Line From InFile Read Next Line Split Line by <Tab> Set Name = Line[0] Set Score = Line[1] If "Julie Milan" = Name Then Set Score = 100 End If Set Line = Name + "<Tab>" + Score Write Line Into OutFile End For Close InFile Close OutFile Delete InFile Rename OutFile to InFile Exit

In C, Merge Sorted Data Files Into Single Output Data File

Image
/** * your name, * the course number, * the date the program was completed, * a brief description of theprogram. */ #include<stdio.h> int merge(const char*, const char*, const char*); int main(){ int error = merge("Data1.txt","Data2.txt","Merged.txt"); if(error){ printf("Error: File merging failed\n"); } else { printf("Success: File merged\n"); } return error; } int merge(const char* n1, const char* n2, const char* n3){ FILE *in1 = fopen(n1, "r"); if(!in1){ printf("Error: Could not read file: %s\n", n1); return 1; } FILE *in2 = fopen(n2, "r"); if(!in2){ fclose(in1); printf("Error: Could not read file: %s\n", n2); return 2; } FILE *out = fopen(n3, "w"); if(!out){ fclose(in1); fclose(in2); printf("Error: Could not write file: %s\n", n3); return 3; } int num1, num2; //until end of file whi...

In Python, Compute Average Of All Numbers In File

Image
def read_all(path): nums = None try: with open(path, 'r') as file: for line in file: if not nums: nums = [] try: nums.append(int(line.strip())) except ValueError: pass except IOError as e: print(e) return nums def average(nums): if not nums: return None total = 0 count = 0 for num in nums: total += num count += 1 return total/count if '__main__' == __name__: nums = read_all('number.dat') print(nums) print('average', average(nums)) Download

In Python, Implementing "tree" Command. Recursively Traverse All Files And Folders.

Image
import os import sys def tree(path): if not os.path.exists(path): print('Path does not exists:', path) return elif os.path.isdir(path): dir = path for path in os.listdir(dir): tree(os.path.join(dir, path)) else: print('File name:', path) with open(path,'r') as file: try: print('File contents:') for line in file: print(line, end='') print('End of file:',path) except UnicodeDecodeError: print('Cannot read binary file!') except IOError: print('Something went wrong!') if '__main__' == __name__: path = os.getcwd() if 1 < len(sys.argv): path = sys.argv[1] tree(path) Download

In Python, Read Integers From File To Compute Sum And Average

Image
  try: with open('numbers.dat','r') as file: total = 0 count = 0 for line in file: line = line.strip() if not line: continue try: num = int(line) total += num count += 1 except ValueError: print('Skipped line:',line) print('sum: %.2f' % total) avg = total/count*1.0 print('avg: %.2f' % avg) except IOError: print('Something went wrong!') Download

Append 100 random integers to binary file with C++/Cpp programming

Image
#include<iostream> #include<fstream> #include<cstdlib> #include<ctime> using namespace std; int main(){ ofstream out("Exercise13_13.dat", (ios::out | ios::binary | ios_base::app)); if(!out){ cerr << "Error: failed to open file!" << endl; return 1; } srand(time(0)); int num; int bytes = sizeof(int); const char *addr = reinterpret_cast<const char*>(&num); for(int i = 1; 100 >= i; i++){ num = rand() % 100; out.write(addr, bytes); } out.close(); return 0; } Download

⚡ Cpp Program 🔥 Artist album tracks #tecqmate

Image
#include<iostream> #include<fstream> #include<string> #include<iomanip> using namespace std; int main(){ ifstream in("namedalbuminfo.txt"); if(!in){ cerr << "Failed to load input file!" << endl; return 1; } ofstream out("namedtracklist.txt"); string line; int hours, mins, sum_hrs = 0, sum_mins = 0, count = 0, diff; getline(in, line); out << "Album title: " << line << endl; getline(in, line); out << "Artist: " << line << endl; cout << "Welcome to 's tracklist generator!" << endl; out << "Tracks:" << endl; out << "--------------------------------------------------" << endl; while(!in.eof()){ count ++; getline(in, line); in >> hours >> mins; in.ignore(); out << setfill('0') << setw(2) << count; out << " - " <...

⚡ C++ SOFT DRINK MACHINE 🔥 #tecqmate

Image

✔ C Sharp Code ⚡ Find avg per student from .csv file 🔥

Image
using System; using System.IO; class Ex{ public static void Main(string[]args){ float avg; string line; string[]parts; using(StreamReader inf = new StreamReader("ex2.csv")){ using(StreamWriter outf = new StreamWriter("ex2-out.csv")){ while(null != (line = inf.ReadLine())){ parts = line.Split(','); avg = ((int.Parse(parts[1])+int.Parse(parts[2])+int.Parse(parts[3]))/3.0f); outf.WriteLine("{0},{1:0.00}",parts[0],avg); } } } } } Download

✔ C Sharp File IO⚡ Find min, max & avg of numbers from .txt file 🔥

Image
using System; using System.IO; class Ex{ public static void Main(string[]args){ int min = 0, max = 0, sum = 0, num, cnt = 0; string line; using(StreamReader file = new StreamReader("ex1.txt")){ while(null != (line = file.ReadLine())){ cnt ++; num = int.Parse(line); sum += num; if(min > num || 1 == cnt) min = num; if(max < num || 1 == cnt) max = num; } } float avg = (sum/(1.0f*cnt)); Console.WriteLine("min: {0}, max: {1}, avg: {2}, sum: {3}", min, max, avg, sum); } } Download

Reading Excel (.xslx) with .Net Core 3 | Tecq Mate

Image
Download