How to write a file with C in Linux?
I want to rewrite the «cp» command of Linux. So this program will work like #./a.out originalfile copiedfile . I can open the file, create new file but can’t write the new file. Nothing is written. What could be the reason?
The current C code is:
4 Answers 4
You need to write() the read() data into the new file:
Update: added the proper opens.
Btw, the O_CREAT can be OR’d (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.
First of all, the code you wrote isn’t portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here’s a version that uses just a single header file and is portable to any platform that implements the C standard library.
EDIT: The glibc reference has this to say:
In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren’t sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).
If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.
Can linux cat command be used for writing text to file?
Is something like this:
Possible? Such that the contents of myfile.txt would now be overwritten to:
This doesn’t work for me, but also doesn’t throw any errors.
Specifically interested in a cat -based solution (not vim/vi/emacs, etc.). All examples online show cat used in conjunction with file inputs, not raw text.
12 Answers 12
That’s what echo does:
Sounds like you’re looking for a Here document
I use the following code to write raw text to files, to update my CPU-settings. Hope this helps out! Script:
This writes the text «performance» to the two files mentioned in the script above. This example overwrite old data in files.
This code is saved as a file (cpu_update.sh) and to make it executable run:
After that, you can run the script with:
IF you do not want to overwrite the old data in the file, switch out
This will append your text to the end of the file without removing what other data already is in the file.
Writing a file to another file in .c
I have a code that reads file and then copies its content to the another file. I need to make it to copy only every 20 symbols and then skip 10 symbols and then again 20 symbols and so on.
I have to use lseek() function but I don’t know how to put all of that in the cycle to do it.
2 Answers 2
or, simplest, with BUFSIZ = 30 :
An additional alternative to consider. There are a number of good points mentioned in the comments to your question. Below the example collects the various comments and provides a concise way to read 30-bytes and write the first 20-bytes to an output file.
The use of all magic numbers (hardcoded values sprinkled throughout the code) are avoided. Both the read and write are validated, stream operations (e.g. fread , fwrite ) are utilized instead of read , write ) and the close of the output file is validated:
(Note: Only full blocks of 20-bytes are written. If the last read is a partial read of less than 20-bytes, that information is not written to the output file. You can adjust the conditionals surrounding fread and fwrite to tailor the behavior to your needs.)
Example Input File (non-POSIX, no eol)
The following input file is text for example purposes, ant it contains no POSIX end-of-line ( ‘\n’ ). (you can include the newline if you like, it will just result in a newline being written to the output file)
Use/Output File
Look it over and let me know if you have any questions.
Writing All Bytes ( 0 fread , you can adjust the conditionals to something similar to the following:
Write file names in to a file
In a directory I have X.txt , Y.txt , Z.txt files. I want to move these filenames into a single file like below:
Any unix command to achieve this?
8 Answers 8
When you are in concerned folder of course.
It is very simple step, you’d just need to redirect the output of ‘ls’ into a file.
Another option to solve this problem is as follow:
If you want file names of text files,
If you want to get file contents together,
Try this tar -cf file.tar X.txt Y.txt Z.txt This will create file.tar you can run the below command to see the output
tar -cf file.tar X.txt Y.txt Z.txt
Shown is the out from my system, means it work for me.
If you want Out_file.txt to contain a sorted list of the name of all the non-hidden files ending in .txt without including Out_file.txt if it wasn’t there beforehand, you can do:
find strikes me as a good choice for the OP’s question, and for many similar objectives:
Recursion and the relative file specification are «free» with find , so this command will gather a list of all .txt files at or below the user’s current dir, and redirect the list to Out_file.txt :
The output will be of the form ./filename.txt , one file per line.
If only the bare filename is wanted in the output (no directory specs), find (most versions) has a built-in printf option:
The output will be of the form filename.txt , one file per line.
If full recursion isn’t wanted (or if «limited recursion» is needed), the maxdepth option is available:
This output will be in the same form as many of the other answers here, but won’t necessarily be sorted in alphabetical order. If alphabetical order is needed, the find output may be piped through sort :
Shell — Write variable contents to a file
I would like to copy the contents of a variable (here called var ) into a file.
The name of the file is stored in another variable destfile .
I’m having problems doing this. Here’s what I’ve tried:
I’ve also tried the same thing with the dd command. Obviously the shell thought that $var was referring to a directory and so told me that the directory could not be found.
How do I get around this?
6 Answers 6
Use the echo command:
The if tests that $destdir represents a file.
The > appends the text after truncating the file. If you only want to append the text in $var to the file existing contents, then use >> instead:
The cp command is used for copying files (to files), not for writing text to a file.
echo has the problem that if var contains something like -e , it will be interpreted as a flag. Another option is printf , but printf «$var» > «$destdir» will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won’t match. However, because printf only interprets backslashes as escapes in the format string, you can use the %s format specifier to store the exact variable contents to the destination file:
printf «%s» «$var» > «$destdir»
None of the answers above work if your variable:
- starts with -e
- starts with -n
- starts with -E
- contains a \ followed by an n
- should not have an extra newline appended after it
and so they cannot be relied upon for arbitrary string contents.
In bash, you can use «here strings» as:
As noted in the comment below, @Trebawa’s answer (formulated in the same room as mine!) using printf is a better approach.
If I understood you right, you want to copy $var in a file (if it’s a string).
When you say «copy the contents of a variable», does that variable contain a file name, or does it contain a name of a file?
I’m assuming by your question that $var contains the contents you want to copy into the file:
This will echo the value of $var into a file called $destdir. Note the quotes. Very important to have «$var» enclosed in quotes. Also for «$destdir» if there’s a space in the name. To append it:
All of the above work, but also have to work around a problem (escapes and special characters) that doesn’t need to occur in the first place: Special characters when the variable is expanded by the shell. Just don’t do that (variable expansion) in the first place. Use the variable directly, without expansion.
Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.
That means, in case of the OP question:
Not the answer you’re looking for? Browse other questions tagged linux bash shell or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.9.18.37632