freopen(3): stream open functions - Linux man page
C library function - freopen() - Tutorialspoint
freopen() function in C language with Example
Can't figure out how to make freopen() work
I want to use freopen so that I don't manually have to type in the scanf and waste time. I want the scanf to accept the stuff inside the file I am trying to read. I have my code linked below. On line 19 and 27 the freopen file data should be used. Source link: https://pastebin.com/fLhcqzLP P.S. I am not sure if I am writing the path correctly. The project folder is personnel_linked_list_database and inside of it is in.txt Thank you :)
Here's the simpler Packcc parser that recognizes a simple list of words and can displays line and columns. The "position" function return the line and colum position of the token. I guess the problem is inside this function.
%auxil "FILE*" # Make the file available in actions. %header{ typedef struct { int line; int column; }Position; Position position(FILE*f, int parsPos); void print_loc(Position p); } list <- line+ {puts("OK");} line <- _ [\n] / _ word _ [\n] word <- [a-z]+ {print_loc(position(auxil, $0s));} _ <- [ \t]* %% int main() { FILE* file = freopen("test.txt", "r", stdin); if(file == NULL) { // try to open. puts("File not found"); } else { // parsing. pcc_context_t *ctx = pcc_create(file); while(pcc_parse(ctx, NULL)); pcc_destroy(ctx); } return 0; } Position position(FILE* f, int parsPos) { Position res = {line: 1, column: 0 }; rewind(f); while (ftell(f) < parsPos) { if (fgetc(f) != '\n') { // Column increases until the end of line.. res.column += 1; } else { // Next line. res.line += 1; res.column = 0; } } return res; } void print_loc(Position p) { printf("%d:%d\n", p.line, p.column); }
[C++] Segmentation Fault while using priority queue
i have tried many things none seem to work, tried with array instead of vectorinstead of while tried to use a for loop(in a small range) in case if it stucks in an infinite loop. with and without typecasting while pushing elements in the queue. Just have no clue what went wrong.
#include using namespace std; priority_queueq; priority_queueq2; std::vectorans; void find_ans(priority_queueq1) { long long int a,b,c; while(!q1.empty() && !q2.empty()) { if(q2.empty()) { a = q1.top(); if((long long int)(a/2) > 0) { q2.push((long long int)(a/2)); ans.push_back(a); } q1.pop(); } else if(q1.empty()) { a = q2.top(); if((long long int)(a/2) > 0) { q2.push((long long int)(a/2)); ans.push_back(a); } q2.pop(); } else { b = q1.top(); c = q2.top(); if(b>c) { if((long long int)(b/2) > 0) { ans.push_back(b); q2.push((long long int)(b/2)); } q1.pop(); } else { if((long long int)(c/2) > 0) { ans.push_back(c); q2.push((long long int)(c/2)); } q2.pop(); } } } } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); //ios_base::sync_with_stdio(false); //cin.tie(NULL); long long int temp,n,m; cin>>n>>m; for(auto i=0;i>temp; q.push(temp); } find_ans(q); for(long long int i=0;i>temp; cout<
This works, now the big question, is there an easy way to reattach stdout and stdin using a c function? I understand I can use tmux/screen, but I'm looking for a minimal solution. Ideally I'd like to restore the process to an identical twin of the original state.
so I am just getting into c++, the system that test my tasks says that my simple program to find the greatest divider takes too long. I have no idea how to make a program run faster. please help! here is the code (ignore the first 2 lines) :
include //Greatest Divisor
using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n, i,d; cin >> n; for (i = 1;i < n;i++) { if (n%i == 0); { d = i; } } cout <
For a project we are writing our own shell, like bash. One of the first features I need to implement for this project is the ability to redirect I/O with < > like in bash. The char* args[] is an array of strings for each argument, including the external command (so if the user entered cat filename, args[0] would be cat and args[1] would be filename). Here is the relevant code: ``` int executeExternalCommand(char* args[1026]) {
int pid = fork(); /** Forked processes **/ /* Child process */ if (pid == 0) { /* I/O Redirect */ int stepindex = 0; while (args[stepindex] != NULL) { if (strcmp(args[stepindex], "<") == 0) { freopen(args[stepindex + 1], "r", stdin); }
// if (args[stepindex] == '<') if (strcmp(args[stepindex], ">") == 0) { int fd = open(args[stepindex + 1], O_CREAT|O_RDWR, 0600); close(1); dup2(fd, 1); } // if(args[stepindex] == '>') stepindex++; }
execvp(args[0], args); // first parameter is the file descriptor (command), second is args array perror(args[0]); exit(127); /* Parent process */ } else if (pid > 0) { int exitStatus; wait(&exitStatus); if (exitStatus != -1) { return 127; } else { return exitStatus; } } else { perror("Fork failed!"); } return -1;
} If I run something like `echo "test" > testfile`, then `cat testfile` the contents of testfile are: "test" > testfile `` Which is obviously wrong. It should just betest` Any idea what I'm doing wrong here? The commented out if statements are placeholders since I'll need to parse those differently. Also ignore the freopen line, I've determined that's not going to work and am just focusing on the output redirect for now.
Can someone explain the logic of marked lines using "//->"... (*1100 CodeForces problem)
Well, I am not sure how it's used here:
int n,t; vector a; int main() { ios_base::sync_with_stdio(0); //freopen("INPUT.txt", "r", stdin); cin>>t; while(t--) { cin>>n; read(a,n); int pos=0; for(int i=0;i ok1&=(a[(pos+i)%a.size()]==i+1); //-> ok2&=(a[(pos-i+a.size())%a.size()]==i+1); } if(ok1 || ok2) cout<<"YES"< Problem: https://codeforces.com/contest/1203/problem/A Part of code taken from user: Soul_Full_Of_Thunder It would be great if someone could explain why Soul_Full_Of_Thunder used that "formula" and is it used anywhere else because I haven't heard of it. Thanks in advance!
Code review: a simple input scanner for stdio and file
same topic here: Code review: a simple input scanner for stdio and file I want to learn rust-lang by solving some algorithm problems. Unfortunately, reading inputs in Rust is not as convenient as in C++ or Python. Especially, I like to read the inputs from file while I am testing or debugging. For example, in C++: c++ freopen("in.txt", "r", stdin); // comment out this line when submit it, that's all int N; cin >> N; So I wrote the following codes. It works, but it is tedious and not elegant(?) Any suggestions would be appreciated. Thank you and sorry for my poor English. ```rust use std::io::{self, BufRead, BufReader}; use std::fs::File; use std::collections::HashMap; struct Scan<'a, T: BufRead + 'a> { cur_pos: usize, // position of cur_line cur_line: Option, // current none blank line reader: &'a mut T } impl<'a, T: BufRead + 'a> Scan<'a, T> { fn new(buf: &'a mut T) -> Self { Scan { cur_pos: 0, cur_line: None, reader: buf } }
fn next_line(&mut self) { let mut line = String::new(); 'outer: loop { self.reader.read_line(&mut line).expect("read error"); for ch in line.chars().next() { if !ch.is_whitespace() { break 'outer; } } } self.cur_pos = 0; self.cur_line = Some(line.trim().to_string()) } fn skip_whitespaces(&mut self) { loop { if self.cur_line.is_none() || self.cur_pos == self.cur_line.as_ref().unwrap().len() { self.next_line(); } if let Some(s) = self.cur_line.as_ref() { // I'm trying to move to the next none whitespace char // this part is tedious, In C++, I can write come code like: // while (this->cur_pos < this->cur_line.size() && iswspace(this->cur_line[this->cur_pos]) { this->cur_pos++; } // but I need to write (let ch = ...) twice here, any suggestions? let ch = s.as_bytes()[self.cur_pos] as char; while self.cur_pos < self.cur_line.as_ref().unwrap().len() && ch.is_whitespace() { self.cur_pos += 1; let ch = s.as_bytes()[self.cur_pos] as char; } if self.cur_pos < self.cur_line.as_ref().unwrap().len() { break; } } } } fn next_char(&mut self) -> char { self.skip_whitespaces(); self.cur_pos += 1; self.cur_line.as_ref().unwrap().as_bytes()[self.cur_pos-1] as char } fn next_string(&mut self) -> String { self.skip_whitespaces(); let mut ret= String::new(); if let Some(s) = self.cur_line.as_ref() { // need improvement here too! // how to put the ch.is_whitespace into while conditions while self.cur_pos < s.len() { let ch = s.as_bytes()[self.cur_pos] as char; self.cur_pos += 1; if ch.is_whitespace() { break; } else { ret.push(ch); } } } ret } fn next_i32(&mut self) -> i32 { let token = self.next_string(); token.parse::().unwrap() } fn next_f64(&mut self) -> f64 { let token = self.next_string(); token.parse::().unwrap() }
let input = io::stdin(); // I want to read the inputs from file while I'm debugging // When I submit it, I just need to comment out the next line let input = File::open("in.txt").expect(""); let mut reader = BufReader::new(input); let mut scan = Scan::new(&mut reader); let N = scan.next_i32(); let mut socks = [0; 101]; let mut mps = HashMap::new(); for i in 0..N as usize { socks[i] = scan.next_i32(); *mps.entry(socks[i]).or_insert(0) += 1; } let mut ans = 0; for (k, v) in mps.iter() { ans += v / 2; } println!("{}", ans);
[Computer Science] I am trying to convert from infix to postfix.I got the algorithm but the code not working properly!
#include "stack.hpp" using namespace std; // Operands are all lower case and upper case characters bool isOperand(char c){ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } int precedence(char c) { if(c == '+' || c == '-'){ return 0; } if(c == '*' || c == '/'){ return 1; } if(c == '^'){ return 2; } return -1; } int main(){ freopen("InfixToPostfix.txt", "r", stdin); string input; string output; // output string string solution; int j = 0; int line_counter = 0; while(cin >> solution){ cin >> input; Stack stack; string result; int x = 0; for(int i=0; i= precedence(input[i]) ) { output += stack.peek(); stack.pop(); } } } //store in result the postfix transformation of 'input' result = output; // Checking whether the result you got is correct if(solution == result){ cout << "line " << line_counter << ": OK [" << solution << " " << result << "]" << endl; }else{ cout << "line " << line_counter << ": ERROR [" << solution << " " << result << "]" << endl; } line_counter++; } }
Here, I was given some made up stack function such as: stack.size(), stack.peek() and stack.push(). They work just like the same as already built-in function for stack. My InfixToPostfix.txt is ab+ a+b abcd^e-fgh*+^*+i- a+b*(c^d-e)^(f+g*h)-i ab+cd+* (a+b)*(c+d) The left handside of the file is the correct result. The right handside is the infix that I need to convert to match the left side. My algorithm idea is:
Whenenver I get the operand ( a b c d ...... ) , I add it to the output string.
Whenever I get the ( (open parenthesis), I push it into the stack.
Whenever I get the ) (closed parenthesis), I will pop out all the element in the stack until the string is empty or I reach another ( parenthesis in the stack.
Whenver I get the operators ( + - / * ^ ), I compare the precedence level of the top of the stack using stack.peek(), and the current operator that the input[i] is at. If the top of the stack is greater or equal than the input[i] , I pop out the top of the stack and add it into the output string. Then I push the current input[i] into the stack.
At the end of the while loop, I assign string result to string output and then compare whether it is correct or not.
My output after complie is: line 0: ERROR [ab+ ab] line 1: ERROR [abcd^e-fgh*+^*+i- ababcd^e-fgh*+i] line 2: ERROR [ab+cd+* ababcd^e-fgh*+iab+cd+] I think my algorithm is pretty close to be all correct. Might need some adjustments. But the code I'm implementing is probably in the wrong syntax or way here.
using namespace std; int main(){ freopen("input.txt.txt", "r", stdin); int TestCase, N, i; int Num[1000]; for(TestCase=0; TestCase<10; TestCase++) { for(i=0; i<1000; i++) Num[i] = 0; cinN; int dem[201]; for (int i =0;i<=200;i++){ dem[i]=0; } for(i=0; i<1000;i++){ cinNum[i]; for (int j =0;j<=200;j++){ if(Num[i] == j){ dem[j]++; break; } } } int max =0; int t =0; for (int i =0; i<=200;i++){ if (max<=dem[i]){ max=dem[i]; t =i; } } cout<< "#" << N << " "< } return 0; } */ //problem 2 /*
include
using namespace std; int main(){ int m[100][100]; int N; freopen("input.txt.txt", "r", stdin); for (int tc =0; tc<10;tc++){ int max =0; cin>>N; for (int i =0; i<100;i++){ for (int j =0; j<100;j++){ cin>>m[i][j]; } } for (int i = 0; i<100;i++){ int tong=0; for (int j = 0; j<100;j++){ tong+=m[i][j]; } if (max<=tong){ max =tong; } } for (int i = 0; i<100;i++){ int tong =0; for (int j = 0; j<100;j++){ tong+=m[j][i]; } if (max<=tong){ max =tong; } } for (int i =0; i<100;i++){int tong =0; tong += m[i][i];if(max<=tong){max = tong;}} for (int i=0; i<100;i++){int tong =0; tong+=m[i][99-i]; if (max<=tong){max=tong;} } cout<<"#"< return 0; } */
include
using namespace std;
define M 100
int main(){
freopen("input.txt.txt", "r", stdin); int TC = 10; for (int tc=0;tc>N; for (int i =0; i>m[i][j]; a[i][j] = m[i][j]; } } int min = 10000; for (int i =0;i0 ){ a[x][y] = 0; y= y-1; dem ++; } else if (a[x+1][y] == 1 && x = dem){min =dem; toado = i;} for (int u = 0;u<100;u++){ for (int v =0;v<100;v++){ a[u][v] = m[u][v]; } } } } cout<<"#"< }
Given a grid of numbers and a maximum area, what is the largest sum you can get from a rectangle of numbers with that area or less? All numbers are in range [1, 100].
So the solution was the find the possible rectangle dimensions, loop through the possible top-left corners, and use a 2D prefix sum array to keep trying to get the highest possible sum. Ghetto code:
#include using namespace std; const int maxWH = 250+2; const int MAXN = 250*250+2; int w, h, n, grid[maxWH][maxWH], pref[maxWH][maxWH], hi, cur; vector > dim; int main() { //freopen("test.txt", "r", stdin); scanf("%d%d%d", &w, &h, &n); for (int i=1; i<=((int)ceil(sqrt(n))); ++i) { dim.push_back({i, n/i}); } for (int i=0; i0) cur -= pref[r-1][c+i.second-1]; if (c>0) cur -= pref[r+i.first-1][c-1]; if (r>0 && c>0) cur += pref[r-1][c-1]; hi = max(hi, cur); } } for (int r=0; r<=h-i.second; ++r) { for (int c=0; c<=w-i.first; ++c) { cur = pref[r+i.second-1][c+i.first-1]; if (r>0) cur -= pref[r-1][c+i.first-1]; if (c>0) cur -= pref[r+i.second-1][c-1]; if (r>0 && c>0) cur += pref[r-1][c-1]; hi = max(hi, cur); } } } printf("%d\n", hi); }
How would I compile and run a .cpp file with a text file as input in the same directory?
Recently I started practice using vim for my coding competition training as my friend's suggestion. The main problem is when i put my test case in a text file with the same directory of the .cpp, It compiled but couldn't read the inputs exactly, thus output some random wrong numbers. I used: freopen("in.txt", "r", stdin); and compile with g++ s.cpp -o test then ./test So for competition purpose, I wonder if there are any other ways editing my .vimrc to get an easier way to testing the input file.
what I want to do is have my application open a console if it is not open in one something equivalent to this code for Windows
if(AllocConsole()) { // If no console is present re open standard streams // AllocConsole() returns zero if already present freopen("CONOUT$", "w", stdout); freopen("CONIN$", "r", stdin); }
I can't seem to find something equivalent for Linux
I am trying to find the issue in my submission for the following contest. http://codeforces.com/blog/entry/16468 I have followed their advice for number D but am still timing out when the input grows pretty large. http://codeforces.com/contest/515/submission/21587588 I am 90% sure this is due to my while loop however when I run that exact code in xcode with freopen('absolute filename','r',stdin); I am unable to get any profiling data and gprof suggests that the tuples being made are my bottleneck. I also saw that people are able to solve this in 1 pass rather than loop multiple times. Any ideas? I would like to know where my logic is wrong or if there is some simple optimization that I have missed rather than just viewing the solutions and translating. copy of code for those who don't want links.
#include #define print(x){std::cout << x << std::endl;} #define ll long long #define pb push_back #define lop(i,n) for(int i=0;i> q; int main() { ios::sync_with_stdio(false); cin >> n >>m; rep(r,0,n){ rep(c,0,m){ cin >>grid[r][c]; } } bool z = true; while(z == true){ // print("HI"); int ct = 0; z = false; rep(r,0,n){ rep(c,0,m){ if(grid[r][c] == '*'){ ct ++; } if(grid[r][c]=='.'){ int deg = 0; bool up = false; bool left = false; bool right = false; bool down = false; if(c+1=0 and grid[r-1][c] == '.'){ deg ++; up = true; } if(c-1>=0 and grid[r][c-1] == '.'){ deg ++; left = true; } if(deg == 1){ z = true; if(left == true){ q.push(make_tuple(r,c-1,'<')); q.push(make_tuple(r,c,'>')); grid[r][c-1]='@'; } else if(up == true){ q.push(make_tuple(r-1,c,'^')); q.push(make_tuple(r,c,'v')); grid[r-1][c]='@'; } else if(down == true){ q.push(make_tuple(r,c,'^')); q.push(make_tuple(r+1,c,'v')); grid[r+1][c]='@'; } else if(right == true){ q.push(make_tuple(r,c,'<')); q.push(make_tuple(r,c+1,'>')); grid[r][c+1]='@'; } } // printf("%d degs\n",deg); } } } // printf("qsize:%d ct:%d and (n*M):%d\n",q.size(), ct, (n*m)); if(q.size()+ct >= (n*m)){ // print("HIIIIT"); z = true; break; } } // print(q.size()); if(z == false){ cout << "Not unique\n"; return 0; } while(q.empty() == false){ // print("HERE"); // exit(0); int x = get<0>(q.front()); int y = get<1>(q.front()); char s = get<2>(q.front()); // printf("%d %d %c\n",x,y,s); if(grid[x][y] == '.' || grid[x][y] == '@'){ grid[x][y] = s; } q.pop(); } show_grid(grid); return 0; }
[C] how to prevent a background process from writing to the terminal
In my OS class, we have an assignment to program a shell with background processing functionality. I believe i have the program putting the process into the background, via the following steps.
setsid() to start new session separate from parent
fork()
umask(0);
chdir();
freopen() for stdin, stdout, and stderr at a new location
as far as various stackoverflow pages have shown, this should be enough, but i'm still getting things printed out to the terminal. On top of this, we're given the heavy suggestion of signals. "your shell must execute the command and return immediately, not blocking until the command finishes. The distinction must be made between backgrounding a process that does not need interactive input and one that does, e.g., the who command vs. the vi command. Concepts: Background execution, signals, signal handlers, process groups, asynchronous execution. System calls: sigset(), sigaction() Signals: SIGTTOU" not sure if i'm missing something or what, but it's getting rather frustrating.
First, attempts to close the file associated with stream, ignoring any errors.Then, if filename is not null, attempts to open the file specified by filename using mode as if by fopen, and associates that file with the file stream pointed to by stream.If filename is a null pointer, then the function attempts to reopen the file that is already associated with stream (it is implementation defined ... The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout). Return Value Upon successful completion fopen (), fdopen () and freopen () return a FILE pointer. Here, we are going to learn about the freopen() function of library header stdio.h in C language with its syntax, example. Submitted by Souvik Saha, on January 11, 2019 freopen() function in C. ... //clear the stdin stream buffer //if we don't write this then after taking string fflush ... The freopen() function is typically used to attach the pre-opened streams associated with stdin, stdout, and stderr to other files. Since implementations are not required to support any stream mode changes when the pathname argument is NULL, portable applications cannot rely on the use of freopen () to change the stream mode, and use of this ... Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode. If filename is a null pointer, the function attempts to change the mode of the stream. Although a particular library implementation is allowed ...
freopen() Function - Ring Programming Language - Lesson 132. Skip navigation Sign in. Search É isso ai. Skip navigation Sign in DONATIVOS https://www.paypal.me/jldrpt Lista de donativos http://www.sys4soft.com/home/youtube/ Vídeos postados diariamente no canal. Subscrevam para fic... Programar em C - Funções freopen e fgets / stdin [Parte 2]- Aula 87 by De aluno para aluno. Aula 2. 4:06. Programar em C - Funções fgetc e getc - Aula 88