PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label file-io. Show all posts
Showing posts with label file-io. Show all posts

Friday, December 9, 2022

[FIXED] How do I check if a directory exists in a Nushell script?

 December 09, 2022     file-io, nushell, shell, syntax     No comments   

Issue

I would like to know how I check if a directory exists in Nushell?


Solution

Use the path exists builtin. Examples:

> "/home" | path exists
true
> "MRE" | path exists
false
> "./nu-0.71.0-x86_64-unknown-linux-gnu" | path exists
true
> [ '.', '/home', 'MRE'] | path exists
╭───┬───────╮
│ 0 │ true  │
│ 1 │ true  │
│ 2 │ false │
╰───┴───────╯
> if ([ '.', '/home', '/proc'] | path exists | reduce -f true { |it, acc| $acc and $it }) {
    "All directories exists"
} else {
    "One ore more directories are missing"
}
All directories exists

See help path exists for more details and help path for more path helper builtins.



Answered By - NotTheDr01ds
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 15, 2022

[FIXED] How to solve "OSError: telling position disabled by next() call"

 November 15, 2022     error-handling, file-io, next, python     No comments   

Issue

I am creating a file editing system and would like to make a line based tell() function instead of a byte based one. This function would be used inside of a "with loop" with the open(file) call. This function is part of a class that has:

self.f = open(self.file, 'a+')
# self.file is a string that has the filename in it

The following is the original function (It also has a char setting if you wanted line and byte return):

def tell(self, char=False):
    t, lc = self.f.tell(), 0
    self.f.seek(0)
    for line in self.f:
        if t >= len(line):
            t -= len(line)
            lc += 1
        else:
            break
    if char:
        return lc, t
    return lc

The problem I'm having with this is that this returns an OSError and it has to do with how the system is iterating over the file but I don't understand the issue. Thanks to anyone who can help.


Solution

I have an older version of Python 3, and I'm on Linux instead of a Mac, but I was able to recreate something very close to your error:

IOError: telling position disabled by next() call

An IO error, not an OS error, but otherwise the same. Bizarrely enough, I couldn't cause it using your open('a+', ...), but only when opening the file in read mode: open('r+', ...).

Further muddling things is that the error comes from _io.TextIOWrapper, a class that appears to be defined in Python's _pyio.py file... I stress "appears", because:

  1. The TextIOWrapper in that file has attributes like _telling that I can't access on the whatever-it-is object calling itself _io.TextIOWrapper.

  2. The TextIOWrapper class in _pyio.py doesn't make any distinction between readable, writable, or random-access files. Either both should work, or both should raise the same IOError.

Regardless, the TextIOWrapper class as described in the _pyio.py file disables the tell method while the iteration is in progress. This seems to be what you're running into (comments are mine):

def __next__(self):
    # Disable the tell method.
    self._telling = False
    line = self.readline()
    if not line:
        # We've reached the end of the file...
        self._snapshot = None
        # ...so restore _telling to whatever it was.
        self._telling = self._seekable
        raise StopIteration
    return line

In your tell method, you almost always break out of the iteration before it reaches the end of the file, leaving _telling disabled (False):

One other way to reset _telling is the flush method, but it also failed if called while the iteration was in progress:

IOError: can't reconstruct logical file position

The way around this, at least on my system, is to call seek(0) on the TextIOWrapper, which restores everything to a known state (and successfully calls flush in the bargain):

def tell(self, char=False):
    t, lc = self.f.tell(), 0
    self.f.seek(0)
    for line in self.f:
        if t >= len(line):
            t -= len(line)
            lc += 1
        else:
            break
    # Reset the file iterator, or later calls to f.tell will
    # raise an IOError or OSError:
    f.seek(0)
    if char:
        return lc, t
    return lc

If that's not the solution for your system, it might at least tell you where to start looking.

PS: You should consider always returning both the line number and the character offset. Functions that can return completely different types are hard to deal with --- it's a lot easier for the caller to just throw away the value her or she doesn't need.



Answered By - Kevin J. Chase
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 12, 2022

[FIXED] Why is file_get_contents faster than memcache_get?

 November 12, 2022     file-io, memcached, php, php-internals     No comments   

Issue

I'm loading XML files from disk using file_get_contents, and as a test I find I can load a 156K file using file_get_contents() 1,000 times in 3.99 seconds. I've subclassed the part that does the loading and replaced it with a memcache layer, and on my dev machine find I can do 1000 loads of the same document in 4.54 seconds.

I appreciate that file_get_contents() will do some caching, but it looks like it is actually faster than a well-known caching technique. On a single server, is the performance of file_get_contents() as good as one can get?

I'm on PHP 5.2.17 via Macports, OS X 10.6.8.

Edit: I've found on XML documents of this size, there is a small benefit to be had in using the MEMCACHE_COMPRESSED flag. 1,500 loads via memcache are done in 6.44 sec (with compression) rather than 6.74 (without). However both are slower than file_get_contents, which does the same number of loads in 5.71 sec.


Solution

Because file_get_contents mmaps the file and so you'll only have a few file system calls and this will end up in the file system cache. memcache involves out-of-process calls to the memcached (and out of server on a clustered implementation).

The performance of file_get_contents() crucially depends on the type of file system, for example a file on an NFS mounted file system is not mmapped and this access can be a LOT slower. Also on a multi-user server, the file system cache can get rapidly flushed by other processes whereas the memcached cache will almost certainly be in memory.



Answered By - TerryE
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] How can I pass the names of a list of files from bash to an R program?

 November 02, 2022     bash, file, file-io, r     No comments   

Issue

I have a long list of files with names like: file-typeX-sectorY.tsv, where X and Y get values from 0-100. I process each of those files with an R program, but read them one by one like this: data <- read.table(file='my_info.tsv', sep = '\t', header = TRUE, fill = TRUE) it is impractical. I want to build a bash program that does something like

#!/bin/bash

for i in {0..100..1}
do
         for j in {1..100..1)
         do
                 Rscript program.R < file-type$i-sector$j.tsv
         done

done

My problem is not with the bash script but with the R program. How can I receive the files one by one? I have googled and tried instructions like: args <- commandArgs(TRUE) either data <- commandArgs(trailingOnly = TRUE) but I can't find the way. Could you please help me?


Solution

At the simplest level your problem may be the (possible accidental ?) redirect you have -- so remove the <.

Then a mininmal R 'program' to take a command-line argument and do something with it would be

#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly = TRUE)
stopifnot("require at least one arg" = length(args) > 0)
cat("We were called with '", args[1], "'\n", sep="")

We use a 'shebang' line and make it chmod 0755 basicScript.R to be runnable. The your shell double loop, reduced here (and correcting one typo) becomes

#!/bin/bash

for i in {0..2..1}; do
    for j in {1..2..1}; do
        ./basicScript.R file-type${i}-sector${j}.tsv
    done
done

and this works as we hope with the inner program reflecting the argument:

$ ./basicCaller.sh 
We were called with 'file-type0-sector1.tsv'
We were called with 'file-type0-sector2.tsv'
We were called with 'file-type1-sector1.tsv'
We were called with 'file-type1-sector2.tsv'
We were called with 'file-type2-sector1.tsv'
We were called with 'file-type2-sector2.tsv'
$ 

Of course, this is horribly inefficient as you have N x M external processes. The two outer loops could be written in R, and instead of calling the script you would call your script-turned-function.



Answered By - Dirk Eddelbuettel
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I append text to a file?

 November 02, 2022     append, file, file-io, shell, text     No comments   

Issue

What is the easiest way to append text to a file in Linux?

I had a look at this question, but the accepted answer uses an additional program (sed) I'm sure there should be an easier way with echo or similar.


Solution

cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter. 
^D

Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.



Answered By - Jon Kiparsky
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 30, 2022

[FIXED] Why is the last line of my input file running twice?

 October 30, 2022     c++, eof, file-io, while-loop     No comments   

Issue

INPUT FILE

Miller Andrew 65789.87 5
Green Sheila 75892.56 9
Sethi Amit 74900.50 6.1

ifstream inFile;
ofstream outFile;
string laastName;
string firstName;
double salary;
double percent;
double new Salary;
double increase;

inFile.open("Ch3_Ex6Data.txt");
outFile.open("Ch3_Ex6Output.dat");

while(!inFile.eof()) {

    inFile >> lastName;
    inFile >> firstName;
    inFile >> salary;
    inFile >> percent;

    percent /= 100;
    increase = salary * percent;
    newSalary = increase + salary;

    outFile << firstName << " " << lastName << " ";
    outFile << setprecision(2) << fixed << newSalary << endl;

}

inFile.close();
outFile.close();

return 0
}

Output File

Andrew Miller 69079.36
Sheila Green 82722.89
Amit Sethi 79469.43
Amit Sethi 74946.19

My question is why is the last line getting output twice and why is it different than the first one? I don't understand why the loop continues on. Is the end of file marker not hitting? I was able to hard code it by putting in an index variable and putting a second condition into the while loop by saying && less than index but i feel as if i shouldn't have to do that whatsoever.


Solution

The problem is that eof does not do what you think it does.

Imagine you are walking on a floor, tile after tile, picking up what's on the floor, putting it in your pockets and show up (print) your pockets content.

When you put you feet on the last tile the floor is not yet "ended" and your nose is still safe. You have not (yet) smashed the wall. You fill-up the pockets and print them.

eof,then, tells you when your nose is broken, not when the tile is the last.

So, you are on the last tile, check your nose, find it ok, and go one step forward. Your nose is now bleeding, nothing is there to peek up to put in our pockets, and your pockets still contain ... what they had before.

You print the content of your pocket (once again) and than check your nose. It's broken: you exit.

The idiomatic way to solve that problem is this one:

while(inFile >> lastName
             >> firstName
             >> salary
             >> percent)
{
   //all your computation here
}

I think you should understand by yourself why.



Answered By - Emilio Garavaglia
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does the program not write to the file?

 October 30, 2022     c, eof, file-io     No comments   

Issue

When I look at this code I do not see anything wrong with it but obviously there is.

What it does:

read two files line by line comparing the sorted integers and placing the lesser into the output file and then reading and placing the next smaller integer into the file.

it is a merge sort of two sorted lists containing only numbers.

one number on each line like so:

1

23

45

56

78

It opens the three files correctly but it does not seem to write anything into the output file.

why is this?

( I apologize for my badly structured code. )

#include <stdio.h>
#include <stdlib.h>

int main ( int argc, char **argv) {

FILE *source_file_one;
FILE *source_file_two;
FILE *destination_file;
int source_file_one_input = 0;
int source_file_two_input = 0;

source_file_one = fopen(argv[1], "rb");
source_file_two = fopen(argv[2], "rb");
destination_file = fopen(argv[3], "w");

if(argc != 4)
    printf("Useage: mergeSort <source_file_1> <source_file_2> <destination_file>\n");

if(source_file_one == NULL)
    printf("Unable to open file one:  %s\n", argv[1]);
    exit(1);

if(source_file_two == NULL)
    printf("Unable to open file two: %s\n", argv[2]);
    exit(1);

while(!feof(source_file_one)) {
    while(!feof(source_file_two)) {
    fscanf(source_file_one, "%d", &source_file_one_input);
    fscanf(source_file_two, "%d", &source_file_two_input);

        if(source_file_one_input > source_file_two_input) {
        fprintf(destination_file, "%d", source_file_two_input); 
        }
        else fprintf(destination_file, "%d", source_file_one_input);
    }
}

fclose(source_file_one);
fclose(source_file_two);
fclose(destination_file);

}

Solution

There are serious logical problems with your program, but the reason you aren't getting any output is missing braces. Without the braces your program simply hits the first exit(1) and quits.

if(argc != 4) {
    printf("Useage: mergeSort <source_file_1> <source_file_2> <destination_file>\n");
    exit(1);
}
if(source_file_one == NULL) {
    printf("Unable to open file one:  %s\n", argv[1]);
    exit(1);
}
if(source_file_two == NULL) {
    printf("Unable to open file two: %s\n", argv[2]);
    exit(1);
}

As a hint on fixing the logical problems, you do not need nested loops!



Answered By - ooga
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is len(file.read()) giving me a value of zero?

 October 30, 2022     eof, file-io, python, python-2.7, seek     No comments   

Issue

Why are the values of print len() different for both functions? Are they not the same?

The file this script is opening was a text file with three lines of text. i named it test.txt and inside it was

Jack and Jill
gave up 
they went home with no water

Code:

def function2nd (filename):
        target = open(theFile, 'r')
        inData = target.read()
        print inData
        print len(inData)
        target.close()
theFile = raw_input("What is the file name?\n>>")
function2nd(theFile)

def function3rd (filename):
        target = open(theFile, 'r')
        target.read()
        print target.read()
        print len(target.read())
        target.close()

function3rd(theFile)

Solution

Files act like a long tape in a casette; you can read the file but by the time you are done you have passed the tape all the way to the end. Reading again won't give you the data again.

As such your second function tried to read data from a file that is already wound all the way to the end.

You can rewind the 'tape' by re-opening the file, or by using target.seek(0) to send it back to the start.



Answered By - Martijn Pieters
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use EOF to read all data from file

 October 30, 2022     c, eof, file-io     No comments   

Issue

I'm learning about file i/o in C language and I wrote this program that reads a file, and then for every even number found, it has to print * to the screen.

My problem is that my program keeps printing * forever.

I have tried different ways,some from this website, but I can't seem to understand how to read until end of a text file using EOF.

I want to learn how to read a text file until the end of the file please. How do I read until the end of a text file? EOF in C.


int main(void)
 {

     int num;
     FILE *ifp;

     ifp = fopen("numbers.txt", "r" );

     if(ifp == NULL)
     {
         exit(1);
     }

     do
     {
         fscanf(ifp, "%d", &num);       

            if(num%2 == 0)

                {
                printf("*\n");
                }
        } while(num != EOF);


    fclose(ifp);

    return 0;
}


Solution

you need to check the result of the scanf

     do
     {
         int result;
         result = fscanf(ifp, "%d", &num);       
         if(result == EOF) break;

         if(result != 1) 
         {
             printf("scanf error\n");
             break;
         }
         if(num%2 == 0)
         {
              printf("*\n");
         }
      } while(1);


Answered By - 0___________
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] How to signify no more input for string ss in the loop while (cin >> ss)

 October 29, 2022     c++, cin, eof, file-io     No comments   

Issue

I used "cin" to read words from input stream, which like

int main( ){
     string word;
     while (cin >> word){
         //do sth on the input word
     }

    // perform some other operations
}

The code structure is something like the above one. It is compilable. During the execution, I keep inputting something like

aa bb cc dd

My question is how to end this input? In other words, suppose the textfile is just "aa bb cc dd". But I do not know how to let the program know that the file ends.


Solution

Your code is correct. If you were interactively inputting, you would need to send a EOF character, such as CTRL-D.

This EOF character isn't needed when you are reading in a file. This is because once you hit the end of your input stream, there is nothing left to "cin"(because the stream is now closed), thus the while loop exits.



Answered By - Mike Lewis
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 28, 2022

[FIXED] How to remove blank elements from an array of strings in C?

 October 28, 2022     arrays, c, c-strings, file-io, is-empty     No comments   

Issue

I was working on file inputs. I wanted to store each line as a string in array. For example: if the file has lines:

This is line 1.
This is line 2.
This is line 3.

The string should contain:

char str[][] = {"This is line 1.", "This is line 2.", "This is line 3."};

When I was trying out with extra spaces:

This is line 1.


This is line 2.
This is line 3.

The output was in the same format. I want to delete those extra empty lines from my array of sentences, so that the output is same as before. How should I do that?

[EDIT] I am using following loop to enter sentences from file to the array:

while (fgets(str[i], LINE_SIZE, fp) != NULL)
{
    str[i][strlen(str[i]) - 1] = '\0';
    i++;
}

Solution

You should use an intermediate one-dimensional character array in the call of fgets like for example

for ( char line[LINE_SIZE]; fgets( line, LINE_SIZE, fp) != NULL; )
{
    if ( line[0] != '\n' )
    { 
        line[ strcspn( line, "\n" ) ] = '\0';
        strcpy( str[i++], line );
    }
}

If a line can contain blanks you can change the condition of the if statement the following way

for ( char line[LINE_SIZE]; fgets( line, LINE_SIZE, fp) != NULL; )
{
    size_t n = strspn( line, " \t" );

    if ( line[n] != '\n' && line[n] != '\0' )
    { 
        line[ n + strcspn( line + n, "\n" ) ] = '\0';
        strcpy( str[i++], line );
    }
}

In the above code snippet you can substitute this statement

strcpy( str[i++], line );

for this statement if you want that the string would not contain leading spaces.

strcpy( str[i++], line + n );


Answered By - Vlad from Moscow
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 5, 2022

[FIXED] how to load first n rows from a scv file with phpexcel?

 October 05, 2022     file-io, file-upload, php, phpexcel     No comments   

Issue

I haven't seen an example on loading the first n rows from afile

So far I have:

$objPHPExcel = PHPExcel_IOFactory::load($file_name);
$sheetData   = $objPHPExcel->getActiveSheet()->toArray(NULL, FALSE, TRUE, FALSE);

The reason I want to load only a few rows is that my file is large (10.000 entries) and im thinking that loading a few rows will be faster.

Any ideas?


Solution

If you want to load only a few rows, then use a read filter (as described in section 5.3 of the reader documentation, entitled Reading Only Specific Columns and Rows from a File (Read Filters)).

If you've already loaded the file and only want to extract a few rows as an array into $sheetdata, then use rangeToArray() instead of toArray()



Answered By - Mark Baker
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 15, 2022

[FIXED] How to check whether print() prints to terminal or file?

 September 15, 2022     file-io, printing, python, python-3.x, terminal     No comments   

Issue

Is there a way in Python 3 to check whether the following command

print('Hello')

prints to the terminal by using

python3 example.py

or prints to the file by using

python3 example.py > log.txt

...? In particular, is there a way to print different things depending on whether I use > log.txt or not?


Solution

I think you're looking for:

writing_to_tty = sys.stdout.isatty()

So...

if sys.stdout.isatty():
    print("I'm sending this to the screen")
else:
    print("I'm sending this through a pipeline or to a file")


Answered By - Thickycat
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 18, 2022

[FIXED] How to write to a file using open() and printf()?

 August 18, 2022     c, file-io, output, printf     No comments   

Issue

I am opening a file with open(), and need to print to that file using printf with no output to the console. How do I do this? I can successfully create the file, and printf to the console, but that is not correct.

int main(int argc, char *argv[]) {
    int fd;
    char *name = "helloworld";
    fd = open(name, O_CREAT);

    char *hi = "Hello World";
    printf("%s\n", hi);

    close(fd);
    exit(0);
}

I need the program to have no output to the console, but if I look at the file helloworld, it should have "Hello World" written inside. Such as:

prompt> ./hello
prompt> more helloworld
   Hello World

Solution

There's a trick to this.

You need to duplicate the open file descriptor to file descriptor 1, i.e. stdout. Then you can use printf:

int main(int argc, char *argv[]){

    int fd;
    char *name = "helloworld";
    fd = open(name, O_WRONLY | O_CREAT, 0644);
    if (fd == -1) {
        perror("open failed");
        exit(1);
    }

    if (dup2(fd, 1) == -1) {
        perror("dup2 failed"); 
        exit(1);
    }

    // file descriptor 1, i.e. stdout, now points to the file
    // "helloworld" which is open for writing
    // You can now use printf which writes specifically to stdout

    char *hi = "Hello World";
    printf("%s\n", hi);

    exit(0);

}


Answered By - dbush
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to show the output in multiple text files in python, for example: print digits from 1 to 10 in 1.txt,2.txt,3.txt

 August 17, 2022     file-io, output, python, python-3.x, text-files     No comments   

Issue

How to show the output in multiple text files in python, for example: print digits from 1 to 10 in 1.txt(o/p-1),2.txt(o/p-2),3.txt(o/p-3) files... Here is a piece of code that I tried, to get the image files as text and store it in individual folders.

     c=-1

     outFile=[] //created a list,as it would overwrite the same outfile multiple times if not used(expecting it to be a different file when list is used)


     for i in range(0, len(onlyfiles)):
                

   `     
         text = pytesseract.image_to_string(images[i])

         c=c+1

         outFile.append(c)

         outFile[c] = open(str1+"outputfile.txt", "w")//str values could be incremented using a different loop/function to have difference in name.
  
         outFile[c].write(text)

         outFile[c].close()

Any modification or new approach is really appreciated.


Solution

for i in images:
    text = pytesseract.image_to_string(i)
    with open(f"{i}.txt", w) as f:
        f.write(text)

Assumption:

  1. We will save the text files (1.txt, 2.txt, .... ) in current directory.
  2. images is an array containing multiple images (not the physical location)


Answered By - Aman Neo
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 15, 2022

[FIXED] Where does an output file go?

 August 15, 2022     c, file-io, output     No comments   

Issue

If you have a program that writes to an output file in C, how do you access/see that output file? For instance, I'm trying to write a program that writes the values from a .ppm image file to another .ppm image file, but I don't know how to access the output file after I've done so. I know that's a pretty general question, but I don't have a block of code I can share just yet.


Solution

When creating a file with fopen by only specifying a file name, without specifying a path, then the file will be put in the current working directory of your program.

If you are using an integrated development environment (IDE) to launch your program, then you can probably see and set your program's initial working directory in your IDE. If you are running your program directly from a command-line shell, then the file will be placed in the current working directory of the shell.

On most operating systems, you can also determine your program's current working directory by calling a certain function provided by the operating system. For example, on POSIX-compliant operating systems, such as Linux, you can call getcwd. On Microsoft Windows, you can call _getcwd or GetCurrentDirectory. That way, you should easily be able to find out in which directory your file is being created.



Answered By - Andreas Wenzel
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to write files to current directory instead of bazel-out

 August 15, 2022     bazel, c++, file-io, output, rules     No comments   

Issue

I have the following directory structure:

my_dir
|
 --> src
|    |
|     --> foo.cc
|     --> BUILD
|
 --> WORKSPACE
|
 --> bazel-out/ (symlink)
| 
| ...

src/BUILD contains the following code:

cc_binary(
    name = "foo",
    srcs = ["foo.cc"]
)

The file foo.cc creates a file named bar.txt using the regular way with <fstream> utilities.

However, when I invoke Bazel with bazel run //src:foo the file bar.txt is created and placed in bazel-out/darwin-fastbuild/bin/src/foo.runfiles/foo/bar.txt instead of my_dir/src/bar.txt, where the original source is.

I tried adding an outs field to the foo rule, but Bazel complained that outs is not a recognized attribute for cc_binary.

I also thought of creating a filegroup rule, but there is no deps field where I can declare foo as a dependency for those files.

How can I make sure that the files generated by running the cc_binary rule are placed in my_dir/src/bar.txt instead of bazel-out/...?


Solution

Bazel doesn't allow you to modify the state of your workspace, by design.

The short answer is that you don't want the results of the past builds to modify the state of your workspace, hence potentially modifying the results of the future builds. It'll violate reproducibility if running Bazel multiple times on the same workspace results in different outputs.

Given your example: imagine calling bazel run //src:foo which inserts

#define true false
#define false true

at the top of the src/foo.cc. What happens if you call bazel run //src:foo again?

The long answer: https://docs.bazel.build/versions/master/rule-challenges.html#assumption-aim-for-correctness-throughput-ease-of-use-latency

Here's more information on the output directory: https://docs.bazel.build/versions/master/output_directories.html#documentation-of-the-current-bazel-output-directory-layout



Answered By - Jin
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 14, 2022

[FIXED] How to write() to a file byte by byte or in chunks in C

 August 14, 2022     byte, c, file-io, output     No comments   

Issue

I'm trying to write byte by byte, 2 bytes, 4 bytes etc in chunks to a file. I currently have this code however am stuck.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>


int main(int argc, char* argv[]){

    char buf[1];

    //creating output file
    int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);

    int infile = open(argv[2], O_RDONLY);

    fread = read(infile, buf, 1);
    printf("%s\n", buf);
    write(outfile);
    close(infile);
    close(outfile)

}

Solution

First of all here I can't see where you had declared fread variable,

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>


int main(int argc, char* argv[]){

    char buf[1];

    //creating output file
    int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);

    int infile = open(argv[2], O_RDONLY);

    fread = read(infile, buf, 1); // here fread var !!?
    printf("%s\n", buf);
    write(outfile);
    close(infile);
    close(outfile)

}

and this is not the way to write in a file, if you succeeded in compilation so according to this you will be able to write only one byte. You have to implement a loop either for loop or while loop in order to write all the byte from one file to another, if I am getting you correctly.

I am assuming here that you are trying to write data byte by byte from one file to another, So with that assumption here is the working code with some changes in your program..

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>


int main(int argc, char* argv[]){
    int fread =0;
    char buf[1]; 

    //creating output file
    int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);

    int infile = open(argv[2], O_RDONLY);
    
    while(fread = read(infile, buf, 1)){ //change here number of bytes you want to read at a time and don't forget to change the buffer size too :)
    printf("%s\n", buf);
    write(outfile, buf, fread);
   }
    close(infile);
    close(outfile)

}


Answered By - Jarvis__-_-__
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, April 28, 2022

[FIXED] How to get rid of IntelliJ warnings/errors on try/catch block's IOException catch?

 April 28, 2022     file-io, intellij-idea, java, try-catch, warnings     No comments   

Issue

I'm sorry. I'm sure this has been answered somewhere here before. However, I can't find it.

Essentially, I have a try/catch block where I seem to get a warning or error no matter what I do. catch(IOException e) results in a "too broad" warning. catch (FileNotFoundException e) results in errors from code that requires an IOException catch. catch (FileNotFoundException | IOException e) results in a "types in multi-catch must be disjoint" error. Finally, putting two catch blocks (one for each exception) results in a "'catch' branch identical to 'FileNotFoundException'" warning.

I don't want to edit IntelliJ's warning system as it is useful.

How can I make the try/catch block below work without warnings or errors?

@Override
public void readFile(File inFile) {

try {
    FileReader fr = new FileReader(inFile);
    BufferedReader br = new BufferedReader(fr);

    // get the line with the sizes of the puzzle on it
    String sizes = br.readLine();

    // find the height of the puzzle
    int height = Character.getNumericValue(sizes.charAt(0));

    // create a puzzleArr with a height
    this.puzzleArr = new char[height][];

    // create the char[] array of the puzzle itself
    int ct = 0;
    String puzzleLine;

    // add the puzzle to puzzleArr
    while (ct < this.puzzleArr.length) {

        puzzleLine = br.readLine().replaceAll("[^a-z]", "");
        this.puzzleArr[ct++] = puzzleLine.toCharArray();
    }

    // create the LinkedList<char[]> of words to find in the puzzle
    String line = br.readLine();
    while (line != null) {

        line = line.toLowerCase().replaceAll("[^a-z]", "");
        this.wordList.add(line.toCharArray());

        line = br.readLine();
    }

    br.close();

} catch (FileNotFoundException e) {

    e.printStackTrace();
}
}

Solution

You can find the corresponding inspection at Settings > Editor > Inspections > Java > Error Handling > Overly broad 'catch' block. I would like to note that this inspection was not enabled by default for me.

There are a couple ways to "fix" the warning.

Use Multi-Catch

@Override
public void readFile(File file) {

    try {
        ...
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

Modify Inspection

This is probably the preferred option, especially if you want to avoid disabling the inspection completely. From the description of the inspection:

Reports catch blocks which have parameters which are more generic than the exceptions thrown by the corresponding try block.

Use the first checkbox below to have this inspection only warn on the most generic exceptions.

Use the second checkbox below to ignore any exceptions which hide other exceptions, but which may be thrown and thus are technically not overly broad.

The last paragraph is what we're interested in.

enter image description here



Answered By - Slaw
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 27, 2022

[FIXED] what does fopen return?

 January 27, 2022     file-io, php     No comments   

Issue

In the following statement :

$handle = fopen('./readme.txt');

what variable is $handle ? Is it a boolean or what ?

I am in a doubt after running these 2 different statements :

if($handle) echo "File opened !"
else echo "Error opening the file !";

and

$line = fgets($handle);

So what variable is actually $handle ?


Solution

It returns either a resource or boolean false. Resources are known as a special type and are explained in detail here



Answered By - juco
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing