When you open a file with fopen, the output you write is buffered, meaning it's not actually send to the lower layers until the buffer is either full or you explicitly flush it with fflush. Also note that the layers under fopen/fprintf/fclose, all the way down to the actual hardware,...
Regular expressions may work for you. Something like Pattern p = Pattern.compile("([a-zA-Z])*([a-zA-Z])\\2([a-zA-Z])*"); Matcher m = p.matcher("zoo"); System.out.println(m.matches()); Just add a loop to try every word in file and if m.matches() == true - delete it. By the way, this won't work if you tYpE lIkE ThIs...
javascript,php,file-handling,strpos,comparison-operators
There are a lot of mistakes in your code. Some of them are already noted. You should use "===" and it's good to trip line-ending symbols. But main problem as I see is that you check in for loop, but exiting after very first string that does not contain correct...
vb.net,linq,loops,file-io,file-handling
I would create a Dictionary or Collection object that you can load from a config file and just check before delete that the file or directory is not in the collection. You are effectively making a white-list of what items should never be removed, which can be modified at any...
python,file,alias,file-handling
In Python 3, the open() function is indeed the same object: >>> sys.version '3.4.2 (default, Nov 29 2014, 18:28:46) \n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)]' >>> id(open) 4467734600 >>> id(io.open) 4467734600 >>> io.open is open True This is not the case in Python 2 however. The io module is...
c#,linq,sorting,io,file-handling
you can use linq to achieve what you want by using the code below var scores = File.ReadAllLines("C:\\asd.txt") .Select(x => x.Split(":".ToCharArray())) // split name and score .Select(x => new { Name = x[0], Score = int.Parse(x[1]) }) // create an object contains name and score for each line .OrderByDescending(x =>...
android,arraylist,file-handling
You're unable to see the file because you used openFileOutput() which creates the file on device's internal storage directory. Files created here are private to your application and aren't even visible to the the user. These files are automatically removed if the user uninstalls the application. To write a file...
c++,ifstream,file-handling,line-endings,seekg
while( file_input.peek() != EOF ) { // code } Basically peek() will read the next char without extracting it. So you can simply compare it to EOF....
The open function is the underlying primitive for the fopen and freopen functions, that create streams. int open (const char *filename, int flags[, mode_t mode]) which creates and returns a new file descriptor for the file named by filename. Initially, the file position indicator for the file is at the...
Using local with $. does something else than you think: Localizing $. will not localize the filehandle's line count. Instead, it will localize perl's notion of which filehandle $. is currently aliased to. $. is not read-only, it can be assigned to normally. 1 while <$fh>; my $i = $.;...
There are two reasons for failure. If your system opens files in text mode by default, it will respond to control characters. So you must open the files in binary mode: p = fopen("three", "wb"); ... q = fopen("three", "rb"); The second failure is the use of the useless feof()....
I have found a way around it using the Dir() function: 'auto check if backup exists - on click Dim i i = 1 file = Dir(path) Do While file <> "" myBool = False isnew = False backup = Right(backup, 6) If InStr(file, backup) > 0 Then myBool =...
You cannot seek on a pipe. Either use a temporary file or store the data in memory. Your choice as to the best solution...
Both of your attempts so far are treating the file as if it were in UTF-8. In the best case, that's going to take twice as much memory - and it's very likely to be invalid data (as UTF-8), basically. You should try specifying the encoding: var text = File.ReadAllText(path,...
c++,input,output,file-handling
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream inFile ("coded.txt"); //explicitly input using ifstream rather than fstream ofstream outFile ("plain2.txt"); //explicitly output using ofstream rather than fstream string str = ""; char ch; while (inFile.get(ch)) { if (ch!='\n' && ch!=' ') { //do your manipulation...
python,linux,search,file-handling
import os #import re -- This module can be used for more advanced processings path = '/home/anmol/Desktop/test/testing/'#path of sample files files = [fiile for fiile in os.listdir(path) if '~' not in fiile] #this generates a list with the non-hidden files, hence using '~' #os.listdir() returns a list of all the...
perl,file-handling,filehandle,filehandler,fileopendialog
It's not easy, first you have to build the data structure needed by the OpenFileDialog api, interact with the system at a low level, track file handles, then get and parse the resulting structure. There are some horrible hacks where you save a windows script, and run it from perl...
You can change your part from: while (partscan.hasNextLine()){ String mystr=partscan.nextLine(); System.out.println(mystr); } partscan.close(); To int lineNo = 0; List<String> theOnesICareAbout = new LinkedList<String>(); while (partscan.hasNextLine()){ String line=partscan.nextLine(); if (isOneOfTheImportantLines(lineNo)) { theOnesICareAbout.add(line); } } partscan.close(); Somewhere you will need a function that tells you if a given line number is one...
python,file,runtime-error,file-handling
You have a typo for i in megadatalist: i.close Should read for i in megadatalist: i.close() ...
A Pure native python library way of solving this - let us know how it compares with bash 828 x 828 should be a walk in the park. Element Column counts: I purposely wrote this with a step in flipping of the sequences, for simplicity and illustrative purposes - you...
When you enter a number for scanf("%d",&a);, you type in a number and press the Enter key. The scanf consumes the number and leaves the newline character ('\n') in the standard input stream (stdin). When the execution of the program reaches gets(name);, gets sees the newline character and consumes it,...
c,file-handling,case-insensitive
I found a few errors in your code, and made a few small tweaks. The errors are - not eating the "whitespace" before the character input, using fgets() instead of fgetc(), using escape characters before the ' symbols in the output text. #include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(void)...
jsp,servlets,hashmap,file-handling
The File constructor needs a real path to access the local directory. So you should not access it using localhost:8080, instead you should access the directory using the real path like below String path="/home/test/apache/webapp/projectname/YouBlogger/Posts/" If you don't want to hard code the path you can use the request.getSession().getServletContext().getRealPath("/") to get...
First of all read Oracle docks on exists. And getAbsoluteFile. Answer yourself what does getAbsoluteFile do? Then answer yourself do you need to get the absolute form of of your folder abstract pathname? Does it help you in anything? If not, use simpliest easy to write easy to read method...
bash,shell,matrix,scripting,file-handling
script_v1.sh: #!/bin/bash compare="/path/to/my/compare_tool" for i in {1..5}; do for j in $(seq $((i+1)) 5); do echo "Comparing $i and $j" compare filename_V000$i.txt filename_V000$j.txt > result_$i_$j.txt done done result_v1: $ > bash script_v1.sh Comparing 1 and 2 Comparing 1 and 3 Comparing 1 and 4 Comparing 1 and 5 Comparing 2...
You can do it like this... var str = @"col1 col2 col3 21312 51245 1235 21311 12 6235"; string[] rows = str.Split('\n') .Select(r => r.Split(' ')[2]) .Skip(1) .ToArray(); ...
You can read the entire file into a String variable and then use String.replaceAll() to replace the characters as you want:- File file = new File("abc.csv"); FileInputStream fis = null; fis = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; fis.read(data); fis.close(); String str = new String(data, "UTF-8"); And then...
You create a buffer with the size ofthe file you want to transfer. With big files you will get just what happened: an OutOfMemoryError, since there is not enough space on your heap for that much data. The easiest fix is to choose a smaller buffer size, like 64k. That...
You have to open the file in append mode: fileobject = open('completed.txt', 'a') Python Docs for opening file "It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception...
excel,vba,excel-vba,file-handling
It's actually the Write statement that puts quotes round the strings. You should use Print instead if you don't want that.
javascript,ajax,regex,file-handling
Use str.split() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split So first we need to split on the newline \n character to get all of the lines. Then for each line, we split on the comma , character to get each of the three substrings, as you say. Here is a verbose but simple way to do...
You need to access the variable $name while writing the name to the file. The way you are doing it now does not add the value of the variable in the string. To do so you can change : $data= 'My fname is $name and My lname is $lname'; to...
ios::in allows input (read operations) from a stream. ios::out allows output (write operations) to a stream. | (bitwise OR operator) is used to combine the two ios flags, meaning that passing ios::in | ios::out to the constructor of std::fstream enables both input and output for the stream. Important things...
Well, if I get it right, you have a dynamic string from DB, which somewhere contents this: '{{URL}}'. So just do simple replace like this: define("URL","http://example.com/mail.php"); $string = str_replace('{{URL}}', '{{' . URL . '}}', $string); This replaces URL text using URL value of that constant...
python,python-3.x,file-handling
Your process is the one that has the file open (via im still existing). You need to close it first before deleting it. I don't know if PIL supports with contexts, but if it did: import os from PIL import Image while True: img_dir = r"C:\Users\Harold\Google Drive\wallpapers" for filename in...
php,mysql,database,file-handling
Actually you have more than one iteration that leads to multiple sheets in same array. foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) { }. So, if your excel contains more than one sheet and the next sheet have no data means blank then it count it as first and insert it to you...
c++,linux,valgrind,file-handling
If multiple threads are using the same FILE* then there are a number of problems you could be hitting if there isn't a lock around all calls to fopen, fclose and fwrite. While you are re-opening the file there may be another thread attempting to write to it. fwrite also...
python,file-handling,with-statement
You could create a "no-op" context manager: import subprocess import contextlib @contextlib.contextmanager def noop(): yield None logging = False file_path = '/tmp/out' with open(file_path, 'wb') if logging else noop() as shell_stdout: subprocess.call(['ls'], stdout=shell_stdout) When logging is True, the conditional expression returns a file object. When logging is False, it returns...
This is because you are mixing formatted input such as cin >> something; and unformatted input such as cin.get(...). The formatted input skis all whitespace before reading data, and stops at the first whitespace after the input. [If you are reading digits, it will also stop on data that is...
php,destructor,file-handling,fclose
I preffer to close the file when no more writing is need or in an exception: try { //write file //close file after all reading operations has been done } catch (Exception $e) { fclose($this->handler); } This is good as an emergency or an uncatched problem, because PHP will close...
That's my proposal. Hope that helps. Basically what it does, it creates three containers (see std::vector from STL). They can have infinite size (you don't have to declare it afront). The create three auxilliary variables which you then use to read from stream. The condition in while loop checks if...
python,file-handling,traceback
The problem is probably when you try to write to the file, in this line: file2.write(forename,surname,score,"\n") The write method receives only one argument. Build a string as pass it as argument. For example: line_to_be_written = str(forename) + " " + str(surname) + " : " + str(score) + "\n" file2.write(line_to_be_written)...
c,text,unicode,file-handling,emoji
In Unicode encoding, emoji must take more than one bytes. Hence printing byte by byte will not help in this case. If you redirect the output to a file, you may get almost same as your file. You may try to print the string by changing locale(on Linux) or you...
java,external,file-handling,file-read
Your scanner is trying to reread the file but it is at the bottom so there are no more lines to read. You have two options: Option 1 Create a new Scanner object for the same file (to start at the beginning again) and then call your while loop on...
bash,scripting,printf,file-handling,gawk
Ignoring the issue of the outer loop and focusing on the awk part of the question, you can use sprintf to produce your filename: gawk -v RS="START_of_LINE_to_SEPARATE" 'NF{ file = sprintf("new_file_%04d.txt", ++n) print RS$0 > file }' "$i" The format specifier %04d means that the number is a digit, padded...
To me, the most straightforward way to avoid relying on the presence of the dummy file is to just catch that exception on the first time through the loop when you try to call close: if re.search('^>[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]', line): try: seqFile.close() except NameError: # Assuming you haven't set seqFile else where...
php,arrays,parsing,file-handling
This should work for you: Just read your file into an array with file() and explode() each line by a space with array_map(). $lines = array_map(function($v){ return explode(" ", $v); }, file("yourTextFile.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES)); ...
"Is there an elegant way to do this?" The warning is because of multiple declarations of $fh, as has already been explained, but I would prefer to see the file selected separately, because There may be more than one file with the desired ID If the file is in dir1...
android,android-manifest,file-handling,systrace
I solved it by reading data from inputstream and writing it to a file try { Process p = Runtime.getRuntime().exec("atrace -t 5 gfx"); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); File myFile = new File("/storage/sdcard0/trac.txt"); FileOutputStream f = null; try { f = new FileOutputStream(myFile); }...
Netdev->queue_fd[class_id] is a file descriptor of Regular file or Any sys/fs entry or Char/Block/Network device file? if it is not a regular file then its size will not be updated after write command. check file tyeps by S_ISREG()...
it would be so much better if have posted an image related to your error!And as php it self has expired the mysql functions it's better to use either PDO or mysqli! i have corrected some part of the codes! please check and let me know if it has helped...
ruby-on-rails,ruby,file-handling
Here is the one way to modify the file content in place. # a.rb File.open "#{__dir__}/out1.txt", 'r+' do |io| r_pos = w_pos = 0 while (io.seek(r_pos, IO::SEEK_SET); io.gets) r_pos = io.tell io.seek(w_pos, IO::SEEK_SET) # line read in by IO#gets will be returned and also assigned to $_. io.puts $_.rstrip w_pos...
php,phpmailer,file-handling,filehandle
You can use the addStringAttachment() method: $mail->addStringAttachment($fileContent,$fileNameToDisplay,$encoding,$type). ...
bash,shell,sorting,matching,file-handling
#!/bin/bash # If there are no files match File_*.*.txt # replace File_*.*.txt by empty string shopt -s nullglob for i in File_*.*.txt; do echo "processing file $i" IFS="_." read foo num1 num2 foo <<< "$i" printf -v dir1 "Dir_%03d" "$num1" printf -v dir2 "Dir_%03d" "$num2" mkdir -pv "$dir1" "$dir2" cp...
typedef struct Quanta { char* name; int Value; int Value1; /* To hold the second integer from line 4 onwards */ struct Quanta *next; } Quanta; Use fgets() to read till end of file and after reading each line use sscanf() to fetch the required data. I have made...
python,list,readfile,file-handling
import re with open("filename") as f: for line in f: if re.match(r"^\d+.*$",line): print line ...
From std::ios::openmode (Section 27.5.3.1.4 of C++11) std::ios::app means to seek to the end of stream before each write. So stream may be not be at end before any write operation. No matter where the pointer is (0 or somewhere else) writing is always done at end. (Implicit seek to end...