Trying to write to a file - c

I am trying to open and then write to a .dat file. The file is just a simple series of numbers, but i would like to add to it. Right now the fputs isn't working for me.
I was wondering if I am using the right function to do the job. Right now it says i can't use the integer enter_this in the function fputs because it is not a constant character.
I want to ask the user to add a integer to the file. My next step after i understand this is to add strings, floats, characters and more. But just getting something that is working is good.
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#include
//functions called
//why is it void?
int main(void)
{
FILE *pFile;
int choice = 0;
char buf[40];
int i = 0;
int num[40];
int enter_this;
printf("WELCOME. \n\n");
pFile = fopen("test.dat", "r");
if (pFile != NULL)
for (i = 0; i < 8; i++)
{
//get num
fgets(buf, sizeof(buf), pFile);
num[i] = atoi(buf);
printf("#%i = %i\n", i, num[i]);
}
printf("Enter number to be added: ");
gets_s(buf);
enter_this = atoi(buf);
fputs(enter_this, pFile);
fclose(pFile);
system("pause");
}//end main

int main(void)
The 'void' in this case implies that the function 'main' accepts no arguments. If you just leave empty parens in C, it implies that the function accepts a variable number of arguments, not 0 as you might expect.
If you want to add a number to the end of the file, you must open it in "append mode":
FILE *pFile = fopen("test.dat", "a");
The second argument "a" is a mode string. It tells fopen to open the file for appending, ie, data will be written at the end of the file. If the file does not exist, it is created. You're currently opening the file in "read only" mode & will not be able to write to it at all. Read about the different mode strings fopen takes here.
Your check to see if the file pointer is NULL is also redundant. You have passed no block to the 'if' to run when the pointer is not NULL. It should be something like:
if (!pFile) {
puts("Something went wrong");
exit(1);
}
Finally, fputs takes a STRING value, ie, a character constant. It will refuse to work with enter_this because it is an integer. One way to write the integer to your file is to use fprintf. For example:
/* Write the integer enter_this & a newline to pFile */
fprintf(pFile, "%d\n", enter_this);

Related

Initializing a null pointer before fscanf

So I gotta make this program that reads a huge .txt file into an AVL, and for that, I need to read all the formatted data in the text document and put it into an AVL. However, any time I try to initialize the AVL in my code (a NULL pointer) it breaks the code once it reaches the fscanf function I used to gather the strings out of the .txt file. I made this demo right here, and I think I'm pretty close to the source of the problem. I narrowed it down to being related to initializing a pointer with a NULL value before the fscanf function. But how do I fix this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE * filePointer = fopen("_lexico_shuf.txt", "r");
if(!filePointer) {
printf("can't open the file");
exit(101);
}
char *lexiconWord;
float polarity;
int *a = NULL;
printf("before while");
while (!feof(filePointer)) {
fscanf(filePointer, "%[^;];%f\n", lexiconWord, &polarity);
printf("| (%s) (%.1f) |", lexiconWord, polarity);
}
printf("after while");
}
so the only thing that is printed on the screen is the "before while" printf, and not the "after while" one. and the program returns a random number.
lexiconWord hasn't been set to point anywhere, so fscanf is using an invalid pointer value to attempt to write to.
Change this variable to an array, and use a field width in fscanf do you don't overrun the buffer, and check the return value of fscanf.
char lexiconWord[100];
...
int rval = fscanf(filePointer, "%99[^;];%f\n", lexiconWord, &polarity);
if (rval != 2) {
printf("not all values read\n");
exit(1);
}
Also, see Why is “while ( !feof (file) )” always wrong?

Assign file content to a variable using C?

How can i read file and assign the file content into variable using C ?
for example: program.txt file is contain values like this
r1=2r2=4r3=5r4=6
i want to read the program.txt file and assign r1,r2,r3,r4 values to variable.
i tried with this example program, but it returns too many argument for fgetchar().
#include <stdio.h>
int main()
{
int n;
char c;
FILE *fptr;
if ((fptr=fopen("E:\\program.txt","r"))==NULL){
printf("Error! opening file");
}
fscanf(fptr,"%d",&n);
fgetchar(fptr);
printf("Value of n=%d",n);
printf("Char is = %c", c);
fclose(fptr);
return 0;
}
the problem is that you ask fscanf to read an integer: fscanf(fptr, "%d", &n);
but your first character in the file is a letter. so fscanf can not find an int so it fails and stop there.
The solution is to write your assignation as one per line like that:
r1=1
r2=2
r3=3
then you ask fscanf to match the line and in place of the number you want to read to put the %d so it looks like that: fscanf(ftpr, "r%d=%d\n", &n, &var);
By the way: fgetchar does not exists, so there is no way your program actually compile, but you can use: fgetc that takes the FILE as argument and returns the next character in the file: char c = fgetc(fptr);
There is no magic way to do this. YOu have to do the heavy lifting yourself
if you can reorg the file so its like Lavigne958 suggests
Then you need to do
int val[10];
while(!feof(fptr))
{
fscanf(ftpr, "r%d=%d\n", &n, &var);
val[n] = var;
}
if they must be called r1, r2, r3, ... then do
int *val[10];
val[1] = &r1; // yes I know I missed out [0]
val[2] = &r2;
...
while(!feof(fptr))
{
fscanf(ftpr, "r%d=%d\n", &n, &var);
*(val[n]) = var;
}

Read Magic Number from .au File

I wrote a small program to get the magic number from an .au file and print it to console, but every time I try, instead of getting the intended .snd, I get .snd$ instead.
I'm not sure why this is happening, considering that I'm only reading in 4 bytes, which is what the magic number is comprised of. So, where is the extra character coming from?
#include <stdio.H>
int main()
{
FILE *fin;
int r;
char m[4], path[20];
scanf("%s", path);
fin = fopen(path, "r");
r = fread(&m, sizeof(char), 4, fin);
printf("magic number is %s\n", m);
return 0;
}
You're printing it as though it were a string, which in C, means that it's NUL-terminated. Change your code like this and it will work as you expect:
char m[5];
m[4] = '\0'; /* add terminating NUL */
Also, you should be aware that scanf is a dangerous function. Use a command line argument instead.
The problem is not how you are reading.
The problem is that your variable is only 4 chars length, and it needs a null character to indicate the end.
printf with %s will print the content of the variable until reach a null character, until that it can print garbage if your variable is not correctly ended.
To fix you can have a bigger variable and set the [4] char with null.
How the new code should look like:
#include <stdio.H>
int main()
{
FILE *fin;
int r;
char m[5], path[20];
scanf("%s", path);
/*Scanf can be dangerous because it can cause buffer overflow,
it means that you can fill your variable with more bytes than it supports, which can end up being used for buffer overflow attacks:
See more: http://en.wikipedia.org/wiki/Buffer_overflow */
fin = fopen(path, "r");
r = fread(&m, sizeof(char), 4, fin);
m[4] = '\0';
printf("magic number is %s\n", m);
return 0;
}

trouble reading a text file

I am trying to read a txt file with following contents:
test.txt
3,4
5,6
7,8
each pair is in one line. I want to put these values in an array. But I want the array size to adjust based on number of pairs in the test txt.
So I calculated the number of lines available in the txt file until EOF and assigned the number of lines to the array to assign the sizeof the array.Then when I try to read the file using fscanf I get some weird numbers which is not even part of this txt file like 2342,123123.
Here is my code:
#include <stdio.h>
int main(int argc , char **argv)
{
FILE *pf;
int k;
int counter=0;
int c;
pf = fopen("test.txt", "r");
if(pf==NULL)
{
printf("its nuull");
}
else
{
do
{
c=fgetc(pf);
if(c=='\n')
counter++;
}while(c!=EOF);
printf("counter value is = %d\n", counter);
int b[counter][2];
for(k=0;k<counter;k++)
{
fscanf(pf,"%d, %d" ,&b[k][0],&b[k][1]);
printf("%d,%d\n" ,b[k][0],b[k][1]);
}
}
fclose(pf);
}
I think you need to call:
rewind(pf);
after displaying your counter value.
This will reset the file pointer to the start of the file.
The issue is probably that the current file pointer is pointing at the end of the file. You need to read from the begining of the file now, so you need to do something like:
rewind(pf);
There are other mechanisms - for instance fseek or fsetpos, but rewind is what I would use here.
You might also check the return from fscanf - this will return the number of input items assigned. If this isn't 2 (in your case) then something went wrong.

File Handling in c not producing the required result

I am new to file handling, when I tried to read data from keypad to file and output the contents of that file on the screen I am not getting the desired result with the code below
/* get data from the keyboared till the end of file and write it to the
file named "input" agian read the data from this file on to the screen*/
#include <stdio.h>
int main()
{
FILE *fp;
char c;
printf("enter the data from the keyboared\n");
fp=fopen("input.txt","w");
while((c=getchar()!=EOF))
{
putc(c,fp);
}
fclose(fp);
printf("reading the data from the file named input\n");
fopen("input.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
return 0;
}
I am getting output something like this h ?
Also is there a way so that i can find out where on the harddisk this file is created?
First up, this is wrong because of precedence.
while((c=getchar()!=EOF))
^
Instead of storing the character, you will continuously store the comparison between the character and EOF. So you will continuously store a long line of 1.
Try this:
while((c=getchar())!=EOF)
^
Second getc and getchar return int. So ch should be int, not char. Using a char could mean the loop will never terminate on some systems.
The line:
fopen("input.txt","r");
Is obviously wrong. Seems you want:
fp = fopen("input.txt","r");
Instead.

Resources