How to skip scanning a line when piping in input? - c

I am trying to pipe in input through stdin in the C programming language. I have a text file that I would like to read, however, the first line is just the header, so I need to somehow skip it and read the rest.
Example:
Name Grade Points Average
Lea A 4.0 3.3
...
I would like to place each line in a node as part of a linked list and so far all I have are the structures. I am unsure of how I am supposed to read the file.
For reference, what type in the command line will be the following:
./codename < input.txt
Thank you!

Use tail with -n:
tail -n+2 input.txt | codename
Alternatively, if you must read the file directly via the < operator, the easiest way is to call getline and throw out the output. You could also do something similar with fgets. You will have to modify the program directly to do that however.

Related

Redirecting file contents into another program in C

Making a basic shell and I need to handle file redirection. Specifically I am stumped on how I can feed data into a program like sort for example from a file.
Something on the command line would look like this:
$ sort < test.txt
How do I accomplish this kind of functionality in my own mini shell made in C?
I thought that maybe sort read from stdin but I guess I can't really write the contents of a file to stdin due to the read only aspect so I'm wondering how I actually get this data into something like sort for example? I am currently using forks and then using execvp() to execute programs.
You need to use freopen.
It works similarly to fopen. The first argument is the filename, the second argument is the mode, and the third argument is the file pointer to redirect. The return value is the new file pointer. So if you want to redirect stdin:
FILE *fp = freopen("input.txt", "r", stdin);
It returns a NULL pointer on failure, just like fopen.

Write an entire program to a file in C

I'm quite new to C programming, but I'm starting to get the hang of it.
For a school assignment, I have written a code in C to play Blackjack.
One of the requirements for the assignment, is that is has to have an option that saves the entire output (everything that's shown in cmd when the program is build and run).
I can't find how to do this anywhere.
Is there a way to write the entire output into a file?
Thanks in advance!
There are 3 ways to achieve what you want.
Use a file. This is the way I recommend. You will need the functions fopen to open a file and enter link description here to print the data in the file. I suggest you read the documentation of the functions in the links and look at the examples.
Redirect stdout to a file using freopen. This basically puts everything that you see now in the console in a file, by adding just one line.
Redirect the output of the program in a file. This is more a shell thing than a C programming technique, but I think it is worth mentioning. In an *NIX environment, the command ./a.out > file.txt will redirect the output of a.out to a file called file.txt in a similar manner freopen does.
You can pipe the stdout and stderr to a file when you build and run. For example, on Linux using the bash shell you can do try this (where the "build_script" is what you use to build and the "a.exe" is the program name):
$ ./build_script >& build_out.txt
$ ./a.exe >& run_out.txt &
The ">&" tells bash to pipe both stdout and stderr to the file. The final "&" in the second line tells bash to run the program in the background. It's hard to tell if this answer will suit your purposes since it's not clear exactly how the game is played from what you have posted. E.g., if you need to use stdin/stdout to play the game then maybe piping the "a.exe" stdout to a file might not work...
I'm assuming simple output redirection is not an option:
$ app > file.txt
Probably, you are using printf to print data to console. Instead of printf, you can use fprintf. fprintf can write data to an arbitrary file, just like printf does to the standard output (which is also a file), in this case the console.
You must first open the file where you will write the output. The command fopen will do this for you:
// this will open or create the file as text to write data.
FILE *f = fopen("my-file.txt", "w");
With the f variable (which you should check for NULL in case of error), you can pass it to fprintf to write data:
fprintf(f, "my super string: %s", string);
Note that despite the first argument being a FILE*, everything else behaves like printf. Actually you can think of printf as a wrapper where the first argument of the fprintf is always stdout.
Do not forget to close your file after you write data!
fclose(f);
This can be done once, after all the data is written to file.
Check the man pages for more info about these commands.
There are more complex (not that much actually) ways of accomplishing this, like using freopen, but I'm leaving this out of the answer. If you need more, update your answer.
EDIT
In your comment, you said you must save or not the output to a file at the end of the program. Well, the file management stuff above you still be usefull. The changes are the following:
You must store the output somewhere in order to decide whether to write to a file or not at the end of the program. Probably you are doing some data formatting with printf. You will have to change your calls from printf to snprintf. This command will write your data to a string, just as printf does prior to output it to the stdout, but it will skip the print-to-output- part.
Then, store the buffer at a list of strings and at the end of the program you write this list to the file or not.
This has some complications: you need a list of strings (a dynamically allocated array of arrays will be enough, actually); how big must your buffer be?
snprintf will return the size required to print the passed data to the buffer, no matter if the buffer is larger or smaller then the given one. But, if it is smaller, you will have to increase its size (reallocating it) and call again snprintf:
char *buffer = malloc(sizeof(char) * 41); // 40 chars + \0!
int size;
if ( size = snprintf(buffer, 41, "your format here", args) > 40 ) {
buffer = realloc(buffer, sizeof(char) * (size + 1));
snprintf(buffer, size + 1, "your format here", args);
}
// now your buffer have the correct data!
// print it to stdout!
puts(buffer);
// store it at the string list.
// execise!
Is left as an exercise wrapping this piece of code in a command to avoid repeat it everywhere you print anything. Also, it is an exercise to create the list of strings.
When you decide to write data to file, instead of use fprintf you can use fputs, as data is already formatted.
I don't know if there is an easier way. I think not.

How Can I Read Specific Parts of a File in C?

I wish to read and write to a .csv file using this format: ~83474\t>wed 19 march 2014\n
When reading, I need to ignore the ~, the tab and the >. They are just there to remind my program of what the values that follow are used for. So far I figured out how to write to file using that format, however, I do not know how to read from the file either. I wish to store the numbers after the ~ as an integer value and the characters after the > as a string. How can I read those two values from every line in the file if each line has the format stated above?
Read the whole line as a string using fgets and process it.

Replacing a word in a file, using C

How do I replace a word in a file with another word using C?
For example, I have a file which contains:
my friend name is sajid
I want to replace the word friend with grandfather, such that the file is changed to:
my grandfather name is sajid
(I am developing on Ubuntu Linux.)
Update:
I am doing filing in C. I have created a .txt file and write some data into it, but as my program progresses I have to search some text and replace it with the other words. The problem I am facing is that suppose in my file I wrote
"I bought apple from the market"
If i replace apple with pineapples as apple has 5 char and pineapple has 9 char it will write it as
"I bought pineapple m the market"
It also has affected the words written after apple.
I have to do it using C, not a command line script.
How about using the exiting Linux sed program?
sed -i 's/friend/grandfather/' filename
That will replace friend with grandfather in the existing file. Make a copy first if you want to keep the original!
Edit:
Alternatively, load the file into an STL string, replace 'friend' with 'grandfather' using a technique such as this, and save the new string into a file.
As you've realized, you won't be able to make the change in place in the original file.
The easy solution is to read each string from the original file and write it to standard output, making the replacement as necessary. In pseudocode:
open original file
while not at end of original file
get next string from original file
if string == "friend"
write "grandfather" to standard output
else
write string to standard output
end while
You can then redirect the output to another file when you execute it, similar to how sed and awk work.
Alternately, you can create a destination file in the code and write to it directly. If you need to replace the original file with the new file, you can use the remove() and rename() library functions in stdio.

Reading from a file

hello i got a problem with reading from a file, i am trying to read from a file using fscanf() and i cant seem to sort it out.
i try to read the file line by line and putting the string in a variable (buffer) each time but i cant understand how the while loop is suppose to be looking like
thanks in advance
the file that i want to read from is a txt file with this format: first line :"1234,abc,etc" second line : "2432,fjh,etc" and more lines like those i want to be able to use the fscanf method inorder to put in each loop the all line lets say "1234,abc,etc" in my string variable and so on till i dont have any more lines to read from
this is what i managed to gather so far (ofc its not the currect way to write it):
char* buffer[100];
while (fscanf(FILE *finput,"%s",buffer)!=something)
{
printf("%s",buffer);
}
i want this code to be able to print all of the lines in my code if you would be able to correct my errors i will greatly appriciate it
I feel like you should read some of these great topics first:
Trouble reading a line using fscanf()
Reading file using fscanf() in C
fscanf multiple lines [c++]
There are plenty of reasons why you should use fgets or something else instead.
Quoting from this place:
fscanf() is a field oriented function and is inappropriate for use in a robust, general-purpose text file reader. It has two major drawbacks:
You must know the exact data layout of the input file in advance and rewrite the function call for every different layout.
It's difficult to read text strings that contain spaces because fscanf() sees space characters as field delimiters.
If you know the size of file you're trying to read, you could use fread(), which is block oriented.

Resources