How to Read data and write data C programming - c

#include <stdio.h>
#include <stdlib.h>
struct customer {
char fname[20],lname[20];
int acct_num;
float acct_balance;
};
void main ()
{
FILE *outfile;
struct customer input;
// open Accounts file for writing
outfile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
exit (1);
}
// instructions to user
printf("Enter \"stop\" for First Name to end program.");
// endlessly read from keyboard and write to file
while (1)
{
// prompt user
printf("\nFirst Name: ");
scanf ("%s", input.fname);
// exit if no name provided
if (strcmp(input.fname, "stop") == 0)
exit(1);
// continue reading from keyboard
printf("Last Name : ");
scanf ("%s", input.lname);
printf("Acct Num : ");
scanf ("%d", &input.acct_num);
printf("Balance : ");
scanf ("%f", &input.acct_balance);
// write entire structure to Accounts file
fwrite (&input, sizeof(struct customer), 1, outfile);
}
FILE *infile;
/*** open the accounts file ***/
infile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
exit (1);
}
while (fread (&input, sizeof(struct customer), 1, infile))
printf ("Name = %10s %10s Acct Num = %8d Balance = %8.2f\n",
input.fname, input.lname, input.acct_num, input.acct_balance);
}
when I input info into the program, it just writes random characters in file .dat and doesn't show the info I have written. Please help me to find the problem of that.

You have:
if (strcmp(input.fname, "stop") == 0)
exit(1);
This ends your program at that point. I don't think you want that. Rather, break your loop:
if (strcmp(input.fname, "stop") == 0)
break;
Also, be sure to close your file after you're done writing to it and before you open it for reading. Otherwise, it may not exist or output to it may not be flushed:
fclose(outfile);
Finally, note that fwrite() will write the binary data of your struct. This will look like garbage to the human eye, even though fread() should read it correctly. But note that you should open the file as binary both for reading and for writing. Otherwise, some systems (Windows, at least) will do some interpreting of the data.
outfile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","wb");
infile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","rb");
With those changes, your code seems to work fine for me.
Be aware that writing and reading binary data in this way can be fraught with peril if you are using different platforms for writing and reading, sending data over a network, or potentially even using different compile options. Byte ordering ("endianness"), data type sizes, and structure padding can all cause you problems. For real-world problems, some kind of portable serialization would be better.

Related

data written to txt file appears in some bizzare language[C]

So I've written a program that will take in a information about a dvd (specifically it's postion, IDkey(just some random number) Title, Genre and Year of release), and using a struct it will write that info to a .txt file called "person.txt". I'm positive my code works for the most part but when I go to test it the output received in the .txt file is written in some weird symbol language and not English and quite frankly I have no idea as to why this is. Any explanation on why this is happening would be much appreciated, thanks :)
PROGRAM
#include <stdio.h>
#include <stdlib.h>
// a struct to read and write
struct dvd
{
int fposition;
int fIdKey;
char ftitle[50];
char fgenre[50];
int fyear;
};
int main ()
{
FILE *outfile;
struct dvd input;
// open file for writing
outfile = fopen ("person.txt", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
printf("Postion: ");
scanf("%d", &input.fposition);
printf("ID Key: ");
scanf("%d", &input.fIdKey);
printf("Title: ");
scanf("%s",&input.ftitle);
printf("Genre: ");
scanf("%s", &input.fgenre);
printf("Year: ");
scanf("%d", &input.fyear);
// write struct to file
fwrite (&input, sizeof(struct dvd), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
// close file
fclose (outfile);
return 0;
}
TEST RUN
TEST RUN OUTPUT IN THE .TXT FILE
You are writing these values to the file:
int fposition;
int fIdKey;
char ftitle[50];
char fgenre[50];
int fyear;
But you are displaying the whole file as characters. That kind of works for ftitle and fgenre because they really are characters...though since you don't populate all 50 characters there are some ugly uninitialized characters shown as well. That is easy to fix: just fill the unused characters (as well as the null terminator) with some known character (such as space) before writing to the file, or do not write the unused characters at all. You can use strlen() to find the length of each string and memset() to set the unused characters to a well-known character which is printable.
Next, saving an int and reading it as text is problematic. You need to decide on a single format. Either you write as integers like now, and you read as integers (which means you need a special program to read the file), or you commit to writing only text to the file.
Easiest might be to only write text to the file. You can use fprintf() for that, instead of fwrite(). You can use fprintf() for the character arrays as well, it will automatically write only the "used" part of each string up to the null terminator, skipping all the "garbage" characters.

How to read a file and compare values in C?

I need to know how could I read a file with values in different lines, and compare it with values I have in memory, to get wich line has a better score, and if values in memory are best, insert those values into the file (the file is open as read and as write at the same time, as this part of code could be run from several fork() at the same time):
if (PuntuacioEquip(jugadors)>MaxPuntuacio && CostEquip(jugadors)<PresupostFitxatges)
{
//Compare with file
int fd, n;
TBestEquip info;
fd = open("best_teams.txt", O_RDONLY);
if (fd<0) panic("open");
while ((n=read(fd, &info, sizeof(info))) == sizeof(info)) {
//printf(cad,"equip %lld, puntuacio %d\n", info.Equip, info.Puntuacio);
//write(1,cad,strlen(cad));
if (info.Puntuacio>PuntuacioEquip(jugadors))
{
fd = open("best_teams.txt", O_WRDONLY|O_TRUNC|O_CREAT,0600);
if (fd<0) panic("open");
sprintf(cad,"%s Cost: %d Points: %d. %s\n", CostEquip(jugadors), PuntuacioEquip(jugadors));
write(fd,cad,strlen(cad));
}
}
// We have a new partial optimal team.
MaxPuntuacio=PuntuacioEquip(jugadors);
memcpy(MillorEquip,&jugadors,sizeof(TJugadorsEquip));
sprintf(cad,"%s Cost: %d Points: %d. %s\n", color_green, CostEquip(jugadors), PuntuacioEquip(jugadors), end_color);
write(1,cad,strlen(cad));
}
Appreciate any help.
Regards,
The best way to iterate through a file is to use the function getline(). Here is an example of its utilisation, taken from this post which I advise you read.
char const* const fileName = "best_teams.txt" ; //
FILE* file = fopen(fileName, "r"); /* should check the result */
if (file != NULL) {
char line[256];
while (getline(line, sizeof(line), file)) { // Each iteration, a line will be stored in string `line`
// Do what you want to do
} // Exits when arrives at the end of the file
else puts("Error while opening file\n");
As suggested in the comments, you can then use fopen("best_teams.txt", "w")
The "w" means write mode, which is described as follow in fopen documentation :
Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
Another solution is to open in read and write mode, and to only change the values you desire, but it might be more complicated.

fscanf while-loop never runs

I'm working on a project, and I can't seem to figure out why a piece of my function for finding prime numbers won't run. Essentially, I want to code to first check the text file log for any previously encountered prime numbers, but no matter what I put for the while-loop containing fscanf(), it seems like my code never enters it.
int filePrime(int a) {
int hold = 0;
FILE *fp = fopen("primes.txt", "a+");
if (fp == NULL) {
printf("Error while opening file.");
exit(2);
}
/*
the while loop below this block is the one with the issue.
on first run, it should skip this loop entirely, and proceed
to finding prime numbers the old-fashioned way, while populating the file.
instead, it is skipping this loop and proceeding right into generating a
new set of prime numbers and writing them to the file, even if the previous
numbers are already in the file
*/
while (fscanf(fp, "%d", &hold) == 1){
printf("Inside scan loop.");
if (hold >= a) {
fclose(fp);
return 1;
}
if (a % hold == 0) {
fclose(fp);
return 0;
}
}
printf("Between scan and print.\n");
for (; hold <= a; hold++) {
if (isPrime(hold) == 1) {
printf("Printing %d to file\n", hold);
fprintf(fp, "%d\n", hold);
if (hold == a)
return 1;
}
}
fclose(fp);
return 0;
}
I have tried all sorts of changes to the while-loop test.
Ex. != 0, != EOF, cutting off the == 1 entirely.
I just can't seem to get my code to enter the loop using fscanf.
Any help is very much appreciated, thank you so much for your time.
In a comment, I asked where the "a+" mode leaves the current position?
On Mac OS X 10.11.4, using "a+" mode opens the file and positions the read/write position at the end of file.
Demo code (aplus.c):
#include <stdio.h>
int main(void)
{
const char source[] = "aplus.c";
FILE *fp = fopen(source, "a+");
if (fp == NULL)
{
fprintf(stderr, "Failed to open file %s\n", source);
}
else
{
int n;
char buffer[128];
fseek(fp, 0L, SEEK_SET);
while ((n = fscanf(fp, "%127s", buffer)) == 1)
printf("[%s]\n", buffer);
printf("n = %d\n", n);
fclose(fp);
}
return(0);
}
Without the fseek(), the return value from n is -1 (EOF) immediately.
With the fseek(), the data (source code) can be read.
One thing slightly puzzles me: I can't find information in the POSIX fopen() specification (or in the C standard) which mentions the read/write position after opening a file with "a+" mode. It's clear that write operations will always be at the end, regardless of intervening uses of fseek().
POSIX stipulates that the call to open() shall use O_RDWR|O_CREAT|O_APPEND for "a+", and open() specifies:
The file offset used to mark the current position within the file shall be set to the beginning of the file.
However, as chux notes (thanks!), the C standard explicitly says:
Annex J Portability issues
J.3 Implementation-defined behaviour
J.3.12 Library functions
…
Whether the file position indicator of an append-mode stream is initially positioned at
the beginning or end of the file (7.21.3).
…
So the behaviour seen is permissible in the C standard.
The manual page on Mac OS X for fopen() says:
"a+" — Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.
This is allowed by Standard C; it isn't clear it is fully POSIX-compliant.

C appending to file after writing

I'm testing out the basic functions to operate files with.
I try to first open/close a file to create it, and then open/close it again to append to it. Lastly, I print out what is in the file.
My code currently looks like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char mark;
/* WRITING: */
file= fopen("goodbye.c","w");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
printf("Enter data to write to .c file:");
while((mark= getchar())!=EOF)
{
putc(mark,file);
}
fclose(file);
/* APPENDING: */
file= fopen("goodbye.c","a");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
char add;
scanf("%c",add);
putc(add,file);
fclose(file);
/* READING: */
file= fopen("goodbye.c","r");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
while((mark= getc(file))!= EOF)
{
printf("%c",mark);
}
fclose(file);
}
With this, I'm not able to append to the file. When using getchar(), I type ctrl+d once finished writing in the first place. After this it goes on to printing out what I just wrote, not giving me the chance to append to the file. Does ctrl+d somehow interrupt with scanf?
And how to get the result that I was looking for?
Your code only allows you to append a single character to the file, which is a little stingy. It can also (at least in theory) lead to problems on some systems if the last line of the text file does not end with a newline, which it won't if you add something other than a newline. Maybe you need a loop to read multiple characters?
Also, since you don't stop the initial input until EOF, you need to clear the 'error' on stdin with clearerr(stdin) to allow further input to occur. This works correctly on Mac OS X 10.10.1 Yosemite; it should work the same on other Unix systems. I can't answer confidently for Windows-based code unless it is using something like Cygwin to simulate Unix, but I expect it would work in much the same way there, too, even with MSVC.
Incidentally, my compiler complains about a missing & in the call to scanf() at:
char add;
scanf("%c",add);
If your compiler doesn't complain, either turn up the warning level or get a better compiler.
This code works as I'd expect:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file;
char mark;
/* WRITING: */
file = fopen("goodbye.c", "w");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
printf("Enter data to write to .c file:");
while ((mark = getchar()) != EOF)
{
putc(mark, file);
}
fclose(file);
printf("EOF 1\n");
/* APPENDING: */
file = fopen("goodbye.c", "a");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
clearerr(stdin);
char add;
while (scanf("%c", &add) == 1)
putc(add, file);
fclose(file);
printf("EOF 2\n");
/* READING: */
file = fopen("goodbye.c", "r");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
while ((mark = getc(file)) != EOF)
{
printf("%c", mark);
}
fclose(file);
return 0;
}
The only substantive changes are adding a loop around the scanf() — though frankly it would be better to use getchar() again, like in the first input loop — fixing the call to scanf(), adding the two printf() statements that report when EOF is detected, and including clearerr(stdin); to allow input to continue.
Sample output
Code without clearerr(stdin):
Enter data to write to .c file:Happiness is a bug-free program.
Happiness is seldom attained.
EOF 1
EOF 2
Happiness is a bug-free program.
Happiness is seldom attained.
Code with clearerr(stdin):
Enter data to write to .c file:Happiness is a bug-free program.
Happiness is seldom attained.
EOF 1
But it helps when you add the clearerr(stdin) to this one.
EOF 2
Happiness is a bug-free program.
Happiness is seldom attained.
But it helps when you add the clearerr(stdin) to this one.

scanf(" %[^\n]", s); then how to strcmp in C?

scanf(" %[^\n]", in);
then for example , i input Knock Knock and hit enter
but my code block inside
if (strcmp ("Knock Knock",out)==0)
does not work
please instruct me ,thanks a lot!
char in[80],out[80];
void input(){
printf("Client: ");
scanf("%[^\n]",in);
fp=fopen("test","w");
if (!fp) return ;
fputs(in,fp);
fclose(fp);
}
fp=fopen("test","r");
fgets(out,81,fp);
fclose(fp);
fp=fopen("test","w");
if (strcmp ("Knock Knock",out)==0)
fputs("Server: Who is there?\n",fp);
First off, the layout of the code is very confusing, and as it stands, it would never compile. You have a function input() that you never seem to call, and you leave code outside the function that should be inside another function, or better yet, all of it should be contained inside a main() function so that it can be executed. Here is a cleaned up example for what you're wanting to-do:
#include <stdio.h>
char in[80],out[80];
int main()
{
printf("Client: ");
scanf("%[^\n]",in); //you really should use fgets() here
FILE* fp = fopen("test.txt","w");
if (!fp)
{
perror("Failed to open file");
return 1;
}
fputs(in,fp);
fputs("\n",fp);
fclose(fp);
fp = fopen("test.txt","r");
if (!fp)
{
perror("Failed to open file");
return 1;
}
fgets(out,80,fp);
fclose(fp);
fp = fopen("test.txt","a+");
if (!fp)
{
perror("Failed to open file");
return 1;
}
if (strcmp ("Knock Knock\n",out)==0)
fputs("Server: Who is there?\n",fp);
return 0;
}
Some important notes:
1) fp has a file-type FILE*, since that is the return of fopen(), but you never declare it as such. So this would never compile with that error.
2) Every time you open a file with the w flag, it erases the entire contents of the file. So if you were intending on appending to the file to have a history of what your output from your program was, you need to use the a+ flag when calling fopen()
3) It would be nice to have some type of error print-out if you failed to open the file rather than scratching your head at why "test.txt" is empty after the program takes the input from stdin. Also if you're going to keep re-opening the file, check for a NULL each time since you're going to get unpredictable results from trying to work with a NULL file pointer (most likely a crash).
4) scanf() can result in nasty buffer over-runs from user-input (or malicious user input) ... use fgets() with stdin to a known-length buffer instead.
You should be able to compile this code now and run it. Works for me with gcc 4.4.3 on Ubuntu. After running, your "test.txt" file should look like:
Knock Knock
Server: Who is there?

Resources