how to print \\ in C? (fprintf) - c

The question how to print one \ is already asked for many times.
I couldn't find anything about printing two backslashes (\\).
When I try to write this:
fputs("\\\\",w_ptr);
there won't be more backslashes than one.
If you are interested:
it's a custom bill writing program which creates Latex PDF with a csv feed.
And there are a lot of double-backslashes in there which indicate a new line feed.
Thanks in advance!

Since you already know how to print one backslash, printing two of them should be easy.
fprintf(file, "%s\n", "\\"); // one backslash
fprintf(file, "%s\n", "\\\\"); // two of them
Oh, and always activate compiler warnings. The first argument to fprintf must be a file pointer, not a string.

Sample program to print two backslashes in file sample.txt:
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
FILE *fp = NULL;
fp = fopen ("sample.txt", "w+");
if ( !fp )
{
printf ("[ERROR]: Opening sample.txt");
}
fprintf (fp, "%s\n", "\\\\");
fclose (fp);
return 0;
}

Related

Why fscanf in c reads csv files wrong?

I am making a linked list of World Cup teams, when loading the teams I need to do a preload reading data from a csv file but reading 2-word countries makes it wrong
For example
Suppose that this is the csv file:
Arabia Saudita, Herve, Renard, Salman, C, 0, 1
First I read the country name, dt name, captain name, group and two numeric values that are part of the program, but the output is something like this:
Country:Arabia DT:Saudita Herve Renard Salman C 0 1 Captain: empty Group:Empty
The expected output would be
Country: Arabia Saudita DtName:Herve DtSurname:Renard CaptainName:Salman Group: C
I tried to do it with a txt file but it is the same since it reads the spaces and the program fails or prints wrong
This is a part of the code that fails
FILE *chargue = fopen("Precharge.csv", "r");
while (!feof(charge)) {
fscanf(charge, "%s\n", countryAux);
chargecountry(&team, countryAux);
fscanf(charge, "%s\n", nameDTAux);
fscanf(charge, "%s\n", surnameDTAux);
chargenameDT(&team, surnameDTAux, nameDTAux);
chargeCapitan(&team, nameCapaux);
fscanf(charge, "%c\n", &groupAux);
chargegropu(&team, groupAux);
fscanf(charge, "%d\n", &actualscoreaux);
chargeactualscore(&team, actualscoreaux);
fscanf(charge, "%d\n", &faseActualaux);
chargeFase(&team, faseActualaux);
insert(lis, team);
forwards(lis);
}
Your format strings parse single words and do not stop at the , separator.
Parsing the csv file (or any file in general) with fscanf() is not recommended as it is very difficult to recover from errors and newlines are mostly indistinguishable from other white space characters. Furthermore, it is incorrect to use while (!feof(charge)) to run this loop.
You can learn Why is “while( !feof(file) )” always wrong? and you should tell you teacher about this. It is a common mistake to use feof() for this pupose.
You should instead read one line at a time with fgets() and use %nnn[^,] conversion specifiers to parse the character fields (nnn being the maximum field length).
Here is an example:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main() {
char buf[256];
char countryAux[100];
char nameDTAux[100];
char surnameDTAux[100];
char groupAux;
int actualscoreaux, faseActualaux;
... // declare team, lis...
FILE *chargue = fopen("Precharge.csv", "r");
if (chargue == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "Precharge.csv",
strerror(errno));
return 1;
}
while (fgets(buf, sizeof buf, chargue)) {
if (sscanf(buf, "%99[^,],%99[^,],%99[^,], %c ,%d ,%d",
countryAux, nameDTAux, surnameDTAux,
&groupAux, &actualscoreaux,&faseActualaux) == 6) {
chargecountry(&team, countryAux);
chargenameDT(&team, surnameDTAux, nameDTAux);
chargeCapitan(&team, nameCapaux);
chargegropu(&team, groupAux);
chargeactualscore(&team, actualscoreaux);
chargeFase(&team, faseActualaux);
insert(lis, team);
forwards(lis);
} else {
printf("invalid record: %s", buf);
}
}
fclose(chargue);
return 0;
}

Why fprintf() doesn't print anything even though the file exists and it's opened and closed correctly?

It's my first exercise about Files and I have to write some code so that if I write a word in the console, it gets printed in the file. The program ends if I input the word "fine" (it's Italian for end). It seems like the file is opened and closed correctly, the program reads the inserted chars, but nonetheless, the file remains blank.
I tried opening the file in various modes, I tried printing how many chars were read, I even tried deleting the file (but it actually does't exit even if I added exit(1).
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
FILE * fp;
char s[64];
if ((fp = fopen("prova.txt", "r+")) == NULL) {
printf("Error.\n");
exit(1);
}
do {
scanf("%s", s);
if (strcmp("fine", s) != 0) {
fprintf(fp, "%s ", s);
}
} while (strcmp("fine", s) != 0);
fclose (fp);
return 0;
}
It should save all the words in a text file, but it remains blank.
Your program looks OK. Most likely, you are checking the wrong file.
An educated guess: you are using some IDE. If this is the case, the file is created, but is created somewhere else. To be sure, print the working directory (man getcwd) somewhere in the beginning of your program, and look for the file there.
you have to use "w" to open a new file with write priviledges
change
if ((fp = fopen("prova.txt", "r+")) == NULL) {
with
if ((fp = fopen("prova.txt", "w+")) == NULL) {
EDIT: Maybe i didn't explained myself, r+ will fail if the file doesn't exist, changing it works for me

fprintf crashes my program when it meets a \n

I am trying to make a report in a .txt file, but when my fprintf meets a \n it crashes. This is my code concerning the opening of the file and crashing:
FILE *f;
f = fopen("estructuras.txt", "w");
fprintf(f, "");
printf("3"); //This is the last thing I see.
fprintf(f, "TEXT TO INPUT\n")
fclose(f);
The problem is you didn't check whether the file opened. If it failed, it will return NULL and that will do bad things to fprintf.
Your first fprintf(f, ""); is a no-op. Printing an empty string does nothing, so that "works" (though I doubt that's guaranteed). printf("3"); does to stdout and is unaffected by the failed fopen. fprintf(f, "TEXT TO INPUT\n") finally tries to print to NULL and pukes.
All system calls have to be checked. They all have different return values on error. fopen returns NULL and the error lies in errno. There's many ways to do fopen error handling, here's one that I like which gives the user information to debug the problem.
#include <string.h> // for strerror()
#include <errno.h> // for errno
#include <stdio.h>
#include <stdlib.h>
int main(){
// Put the filename in a variable so it can be used in the
// error message without needing to be copied.
char file[] = "estructuras.txt";
FILE *fp = fopen(file, "w");
if( fp == NULL ) {
// Display the filename, what you were doing with it, and why it wouldn't open.
fprintf(stderr, "Could not open '%s' for writing: %s\n", file, strerror(errno));
exit(-1);
}
}
strerror(errno) turns the numeric errno error code into a human readable string. There are quotes around the filename in case extra whitespace snuck in.
So you'll get an error like Could not open 'estructuras.txt': No such file or directory.

C Read and write file at the same time [duplicate]

I'm testing the usage of fprintf() and it is not working. When I first wrote the code I forgot to add \n inside fprintf() and it worked. However, when I added \n at the start of "test 1 2" it stopped working.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE* f = fopen("test.txt", "r+");
if( f == NULL) return 0;
char str[4][10];
for(int a = 0; a <= 3; ++a)
{
fscanf(f, " %[^\t\n]s", str[a]);
printf("%s\n", str[a]);
}
fprintf(f, "\ntest 1 2\n");
fclose(f);
system("pause");
return 0;
}
and my test.txt contains ( instead of \t and \n I pressed tab and enter in the file but I couldn't manage it here)
a b\t c d\t e\n
f g
For files open for appending (those which include a "+" sign), on
which both input and output operations are allowed, the stream should
be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between
either a writing operation followed by a reading operation or a
reading operation which did not reach the end-of-file followed by a
writing operation.
Source
So add this:
fflush(f);
before your fprintf if you want to append to the file without deleting its previous contents, or this:
rewind(f);
if you want to overwrite the content, as pointed by your comment.

C, reading a multiline text file

I know this is a dumb question, but how would I load data from a multiline text file?
while (!feof(in)) {
fscanf(in,"%s %s %s \n",string1,string2,string3);
}
^^This is how I load data from a single line, and it works fine. I just have no clue how to load the same data from the second and third lines.
Again, I realize this is probably a dumb question.
Edit: Problem not solved. I have no idea how to read text from a file that's not on the first line. How would I do this? Sorry for the stupid question.
Try something like:
/edited/
char line[512]; // or however large you think these lines will be
in = fopen ("multilinefile.txt", "rt"); /* open the file for reading */
/* "rt" means open the file for reading text */
int cur_line = 0;
while(fgets(line, 512, in) != NULL) {
if (cur_line == 2) { // 3rd line
/* get a line, up to 512 chars from in. done if NULL */
sscanf (line, "%s %s %s \n",string1,string2,string3);
// now you should store or manipulate those strings
break;
}
cur_line++;
}
fclose(in); /* close the file */
or maybe even...
char line[512];
in = fopen ("multilinefile.txt", "rt"); /* open the file for reading */
fgets(line, 512, in); // throw out line one
fgets(line, 512, in); // on line 2
sscanf (line, "%s %s %s \n",string1,string2,string3); // line 2 is loaded into 'line'
// do stuff with line 2
fgets(line, 512, in); // on line 3
sscanf (line, "%s %s %s \n",string1,string2,string3); // line 3 is loaded into 'line'
// do stuff with line 3
fclose(in); // close file
Putting \n in a scanf format string has no different effect from a space. You should use fgets to get the line, then sscanf on the string itself.
This also allows for easier error recovery. If it were just a matter of matching the newline, you could use "%*[ \t]%*1[\n]" instead of " \n" at the end of the string. You should probably use %*[ \t] in place of all your spaces in that case, and check the return value from fscanf. Using fscanf directly on input is very difficult to get right (what happens if there are four words on a line? what happens if there are only two?) and I would recommend the fgets/sscanf solution.
Also, as Delan Azabani mentioned... it's not clear from this fragment whether you're not already doing so, but you have to either define space [e.g. in a large array or some dynamic structure with malloc] to store the entire dataset, or do all your processing inside the loop.
You should also be specifying how much space is available for each string in the format specifier. %s by itself in scanf is always a bug and may be a security vulnerability.
First off, you don't use feof() like that...it shows a probable Pascal background, either in your past or in your teacher's past.
For reading lines, you are best off using either POSIX 2008 (Linux) getline() or standard C fgets(). Either way, you try reading the line with the function, and stop when it indicates EOF:
while (fgets(buffer, sizeof(buffer), fp) != 0)
{
...use the line of data in buffer...
}
char *bufptr = 0;
size_t buflen = 0;
while (getline(&bufptr, &buflen, fp) != -1)
{
...use the line of data in bufptr...
}
free(bufptr);
To read multiple lines, you need to decide whether you need previous lines available as well. If not, a single string (character array) will do. If you need the previous lines, then you need to read into an array, possibly an array of dynamically allocated pointers.
Every time you call fscanf, it reads more values. The problem you have right now is that you're re-reading each line into the same variables, so in the end, the three variables have the last line's values. Try creating an array or other structure that can hold all the values you need.
The best way to do this is to use a two dimensional array and and just write each line into each element of the array. Here is an example reading from a .txt file of the poem Ozymandias:
int main() {
char line[15][255];
FILE * fpointer = fopen("ozymandias.txt", "rt");
for (int a = 0; a < 15; a++) {
fgets(line[a], 255, fpointer);
}
for (int b = 0; b < 15; b++) {
printf("%s", line[b]);
}
return 0;
This produces the poem output. Notice that the poem is 14 lines long, it is more difficult to print out a file whose length you do not know because reading a blank line will produce the output "x�oA". Another issue is if you check if the next line is null by writing
while (fgets(....) != NULL)) {
each line will be skipped. You could try going back a line each time to solve this but i think this solution is fine for all intents.
I have an even EASIER solution with no confusing snippets of puzzling methods (no offense to the above stated) here it is:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;//read the line
ifstream myfile ("MainMenu.txt"); // make sure to put this inside the project folder with all your .h and .cpp files
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Happy coding

Resources