Creating text file in C, using VC++ Express - c

Okay this is kind of an odd question, but I have no idea why this doesn't work...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME 15
#define MAX_SUBSEC 3
#define N 128
struct student{
int term;
int id;
char lastname[MAX_NAME];
char firstname[MAX_NAME];
char subjectnam[MAX_SUBSEC];
int subject;
int catalog;
char section[MAX_SUBSEC];
}students[10];
int main(){
int i;
char poop[10];
char fname[128];
printf("Enter the name of the text file: ");
scanf("%123s",fname);
strcat(fname,".txt");
FILE *inputf;
inputf = fopen(fname,"w");
if (inputf == NULL){
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
printf("Enter first name: "); scanf("%s", poop);
fprintf(inputf, "%s\n", poop);
for (i=0; i<=10; ++i)
fprintf(inputf, "%d, %d\n", i, i*i);
fclose(inputf);
return 0;
}
Now the end of this code is just me practicing creating the file and writing to it and all that good stuff. When I coded this and ran it on my Mac using NetBeans it worked fine, I'm doing this all in C by the way, NOT C++. Now I want to do it here on my desktop and Visual wont have it, doesnt do anything but open the cmd window, take in the first line where it says to enter the file name, I do and press enter and the program closes down and terminates. I have added the source file item and named it with the proper *.c extension, and I have coded *.c in this IDE before but never had to create a file til now, which I can guarantee is the issue. Anyone have any idea why this all happens?
EDIT: I've broken up some code to try and pinpoint the issues and it seems as though these lines are the cause...
FILE *inputf;
inputf = fopen(fname,"w");
When I attempt to build and run I get some typical VC error message and this in my output about these "indiscretions"
"error C2275: 'FILE' : illegal use of this type as an expression"
"error C2065: 'inputf' : undeclared identifier"
"warning C4047: '=' : 'int' differs in levels of indirection from 'FILE *'"
So why is it that these lines work totally fine on NetBeans on my Mac, but not here on Windows? Some sort of portability issue I imagine?

This is happening because CL.exe(Microsoft Compiler) does not allow declaration of variables in code. It requires you define variables at the start of a function or a block.
Sadly, even though it is C99 standard, Even CL.exe for MSVC++ 2010 does not support it!
Change your code to:
int main(){
int i;
char poop[10];
char fname[128];
FILE *inputf;
printf("Enter the name of the text file: ");
scanf("%123s",fname);
strcat(fname,".txt");
inputf = fopen(fname,"w");
if (inputf == NULL){
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
printf("Enter first name: "); scanf("%s", poop);
fprintf(inputf, "%s\n", poop);
for (i=0; i<=10; ++i)
fprintf(inputf, "%d, %d\n", i, i*i);
fclose(inputf);
return 0;
}

Related

I'm trying to write a specific number of lines in a file but I keep getting a blank line as the first one

i'm new here and i'm trying to solve a FILE problem in c. Basically i have to create a program that lets the user input how many lines he wants to write in a file, create a new file, write those lines and the reading it and establish how many lines where written and print the number of lines.
int main() {
int x, lc=0;
char str[100];
FILE *fp=fopen("test.txt","w");
if (fp==NULL) {
printf("\nOpening failed");
}else{
printf("\nOpened correctly");
}
printf("\nStrings to write:\n");
scanf("%d",&x);
for (int i = 0; i < x; i++) {
fgets(str, sizeof str, stdin);
fputs(str,fp);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL) {
lc++;
}
fclose(fr);
printf("\nThere are %d lines",lc);
return 0;
}
If i leave the code like this it messes up with my for cycle and it only lets me write 3 lines because it does put a free line at the start of the file. Can you explain how do i solve that? or if it's just how fgets and fputs behave and i have to remember that blank line at the start. Thank you in advance. (i'll leave a file output as follows with numbers for the lines)
1)
2)it seems to work
3)dhdhdh dhdh
4)random things
As you can tell from the comments, there are a lot of ways to approach this task. The usage of "scanf" and "fgets" can get complex especially if mixed within the same reading task. But, just to give you one option as to deriving a solution, following is a snippet of code to offer one of many possible routes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x, lc=0;
char str[101];
FILE *fp=fopen("test.txt","w");
if (fp==NULL)
{
printf("Opening failed\n");
}
else
{
printf("Opened correctly\n");
}
printf("Strings to write: ");
scanf("%d",&x);
for (int i = 0; i < x; i++)
{
printf("Enter string: ");
scanf("%s", str);
fprintf(fp, "%s\n", str);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL)
{
lc++;
}
fclose(fr);
printf("\nThere are %d lines\n",lc);
return 0;
}
You will note that both "scanf" and "fgets" are being used in this example, but not in reference to the same file. For user input, "scanf" is getting used. Once the file is closed and then reopened for reading, "fgets" is being used for that portion of the task.
Testing this program snippet out resulted in matching up the same quantity of lines read from the file as were entered.
#Una:~/C_Programs/Console/FileWrite/bin/Release$ ./FileWrite
Opened correctly
Strings to write: 4
Enter string: Welcome
Enter string: to
Enter string: Stack
Enter string: Overflow
There are 4 lines
Give it a try and see if it meets the spirit of your project.

Save a struct into a file then read it in the same program

I have this struct which I stack with information, I'm doing that via pointers, after doing that I'm saving all the info into a file named person.txt and then read it in the same program.
The problems I'm having are:
I can display the final result correctly, but, the person.txt file doesn't have any meaningful text in it, it's just a bunch of unknown symbols for me (I guess it's automatically saved in bit, but I don't know why it does that).
After inserting the info and the .txt file is created and the result is displayed, after closing the program, when trying to use only the code to read the file (meaning I make a commentary out of the code I won't need), it displays me something else, totally different of what I initially introduced.
Heres the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct eu
{
char name[30];
int age,weight, number;
};
int main()
{
struct eu *Eu1, euptr;
Eu1 = &euptr;
printf("Name & Surname:");
scanf("%[^\n]", Eu1->name);
printf("\n");
printf("Age:");
scanf("%d", &Eu1->age);
printf("\n");
printf("Weigt(kg):");
scanf("%d", &Eu1->weight);
printf("\n");
printf("Telephone number:");
scanf("%d", &Eu1->number);
printf("\n\nDisplay: ");
FILE *outinfo;
outinfo = fopen("person.txt", "a");
if (outinfo == NULL)
{
fprintf(stderr, "\nSomething went wrong!\n");
}
fwrite(&Eu1, sizeof(struct eu),1,outinfo);
fclose(outinfo);
outinfo = fopen("person.txt", "r");
while(fread(&Eu1, sizeof(struct eu), 1, outinfo))
printf ("\n Name:%s\n Age:%d\n Weight:%d\n Tel. Number:%d\n ", Eu1->name, Eu1->age, Eu1->weight, Eu1->number );
fclose (outinfo);
return 0;
}
you've messed the pointers. It is ok to save whole struct into the file, here is correctly working code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct eu
{
char name[30];
int age,weight, number;
};
int main()
{
struct eu eu1, *euptr;
euptr = &eu1;
printf("Name & Surname:");
scanf("%[^\n]", euptr->name);
printf("\n");
printf("Age:");
scanf("%d", &euptr->age);
printf("\n");
printf("Weigt(kg):");
scanf("%d", &euptr->weight);
printf("\n");
printf("Telephone number:");
scanf("%d", &euptr->number);
printf("\n\nDisplay: ");
FILE *outinfo;
outinfo = fopen("person.txt", "a");
if (outinfo == NULL)
{
fprintf(stderr, "\nSomething went wrong!\n");
}
fwrite(euptr, sizeof(struct eu), 1, outinfo);
fclose(outinfo);
outinfo = fopen("person.txt", "r");
while(fread(&eu1, sizeof(struct eu), 1, outinfo))
printf ("\n Name:%s\n Age:%d\n Weight:%d\n Tel. Number:%d\n ", euptr->name, euptr->age, euptr->weight, euptr->number );
fclose (outinfo);
return 0;
}
I've swapped eu1 & euptr variables for more logical naming.
fwrite will write the raw data you have given it, for the number of bytes you have specified. You are able to write this struct and read it back which is exactly what you are trying to do, all is working as intended. "Normal" text files with words use a particular encoding (usually ascii or unicode), and you need to use that encoding if you want it to be readable.
If you wanted this to be human readable, you would need to specify a format. A very simple one would be CSV (comma separated values).
So you might do something like
fprintf(outinfo, "%s,%d,%d,%d", Eu1.name, Eu1.age, Eu1.weight, Eu1.number);
//...
fseek(outinfo,0,SEEK_SET);// move to beginning of file
fscanf(outinfo, "%s,%d,%d,%d", &Eu2.name, &Eu2.age, &Eu2.weight, &Eu2.number);
this doesn't involve any error checking, and would need to be changed if your struct format changed, but would allow the file to be human readable if that was a requirement for you.

Fprintf not printing

I've been trying to do file excercises in C but when I run programs from the professor or tutorials (which should work), the file always comes out blank. Is there a solution to this?
My computer is pretty old, but it can still run various programs, I don't undersand why it doesn't work with files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*program that prints on a file your shopping list*/
int main(int argc, char **argv)
{
FILE *fp= fopen("Shopping list.txt", "w");
int end= 0; //have you finished writing the articles
char article[80]; //the article you want to buy
int n; //quantity
while(!end){
printf("What do you need to buy? ");
fgets(article, 80, stdin);
article[strlen(article)- 1]= '\0';
fprintf(fp, "%s ", article);
printf("How much of it? ");
scanf("%d", &n);
fprintf(fp, "%d\n", n);
printf("Are you done? (1= Yes, 0= No) ");
scanf("%d%*c", &end);
}
fclose(fp);
}
It should print out on the file (which is created and remains empty) your input. There is no error message
I've resolved the problem by simply specifying the absolute path in fopen

Letter guessing game in C program, confused of errors

I am trying to do a letter guessing game in C language by using Visual Studio 2012, but I keep getting errors and warnings and I have no clue how to fix them. The errors that I keep receiving are:
1.)Warning 1 warning C4133: 'function' : incompatible types - from 'FILE *' to 'const char *'
2.)Warning 2 warning C4047: '=' : 'FILE *' differs in levels of indirection from 'int (__cdecl *)(FILE *)'
3.)Error 3 error C2449: found '{' at file scope (missing function header?)
4.)Error 4 error C1004: unexpected end-of-file found
5.)IntelliSense: argument of type "FILE *" is incompatible with parameter
6.)IntelliSense: a value of type "int (__cdecl *)(FILE *_File)" cannot be assigned to an entity of type "FILE *"
I also see errors that say 'expected a declaration.'
Every time I try to fix things, I end up causing more issues in other areas. Could someone give me assistance with this? Thank you!
Here is my code:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#define MAXGUESSES 5
int SingleGame(char file_letter);
int main()
{
//declare additional variables
int PlayGames = 4,
i = 0;
FILE * infile;
char letter;
//display instructions
printf("Welcome to the Letter Guessing Game!\n");
printf("You will enter the number of games that you want to play, which is 1-4 games\n");
printf("You have 5 chances to guess each letter\n");
printf("Let's begin!\n");
//open file
infile = fopen("lettersin.txt", "r");
//get number of games to play
printf("How many games would you like to play?(1-4)\n");
scanf("%d", &PlayGames);
for(i=0;i<PlayGames;i++)
{
//get a letter from file
scanf(infile, " %c", &letter);
//Play one game
printf("Let's play a game %d\n", i);
//check for win or lose
SingleGame (letter);
}
//close file
infile = fclose;
return 0;
}
int SingleGame(char file_letter);
{
//Function definitions
int numGuesses = 0;
while(numGuesses < MAXGUESSES);
char RetrieveGuess = 0;
int PlayGames = 0;
{
printf("Enter a guess\n");
scanf("%c" , &RetrieveGuess);
if(file_letter == RetrieveGuess);
{
printf("You guessed it!\n");
}
else
{
if(file_letter>RetrieveGuess)
{
printf("The letter you are trying to guess comes before:%d\n",RetrieveGuess)
}
{
else if(file_letter<RetrieveGuess)
{
printf("The letter you are trying to guess comes after:%d\n", RetrieveGuess)
}
{
numGuesses = numGuesses +1;
}
1.)Warning 1 warning C4133: 'function' : incompatible types - from 'FILE *' to 'const char *'
scanf(infile, " %c", &letter);
If you want to read from a specific FILE *, use fscanf():
fscanf(infile, " %c", &letter);
2.)Warning 2 warning C4047: '=' : 'FILE *' differs in levels of indirection from 'int (__cdecl *)(FILE *)'
infile = fclose;
You want to call fclose() and not assign it to infile (which also doesn't have a compatible type):
fclose(infile);
3.)Error 3 error C2449: found '{' at file scope (missing function header?)
int SingleGame(char file_letter);
The semicolon makes that a function declaration/protoype, but you want to define one. Delete it.
The semicolon here is a so-called null statement). This means if both variables are equal, then nothing will be done.
if(file_letter == RetrieveGuess);
You have a number of issues with your code here. It is always difficult to work on more than one problem at a time. My advice is that you copy all this code into a different file, and rebuild this file one line at a time and only add another line after you compile the current file error and warning free.
Lots of syntax errors were in code. I've corrected them for you. Although not sure logically the code is correct or not. You got to run and see.
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#define MAXGUESSES 5
void SingleGame(char file_letter);
int main()
{
//declare additional variables
int PlayGames = 4,
i = 0;
FILE* infile;
char letter;
//display instructions
printf("Welcome to the Letter Guessing Game!\n");
printf("You will enter the number of games that you want to play, which is 1-4 games\n");
printf("You have 5 chances to guess each letter\n");
printf("Let's begin!\n");
//open file
infile = fopen("lettersin.txt", "r");
//get number of games to play
printf("How many games would you like to play?(1-4)\n");
scanf("%d", &PlayGames);
for(i=0;i<PlayGames;i++)
{
//get a letter from file
fscanf(infile, " %c", &letter);
//Play one game
printf("Let's play a game %d\n", i);
//check for win or lose
SingleGame (letter);
}
//close file
fclose(infile);
return 0;
}
void SingleGame(char file_letter)
{
//Function definitions
int numGuesses = 0;
while(numGuesses < MAXGUESSES)
{
char RetrieveGuess = 0;
int PlayGames = 0;
printf("Enter a guess\n");
scanf("%c" , &RetrieveGuess);
if(file_letter == RetrieveGuess)
{
printf("You guessed it!\n");
}
else
{
if(file_letter>RetrieveGuess)
{
printf("The letter you are trying to guess comes before:%d\n",RetrieveGuess);
}
else if(file_letter<RetrieveGuess)
{
printf("The letter you are trying to guess comes after:%d\n", RetrieveGuess);
}
numGuesses = numGuesses +1;
}
}
}

how to store and read data from files

I am new to C in linux. I am trying to store data to file and read them back. Is this the correct way. When I try to compile this i am getting errors. Can anyone help me please. thanks in advance.
#include<stdio.h>
typedef struct
{
int select;
char lastname[25];
char firstname[25];
char address[25];
char phonenumber[25];
} addressbook;
addressbook a[5];
FILE *fp;
int main()
{
int i;
for( i=0; i<5 ; i++)
{
printf("enter details\n");
printf("enter lastname:\n");
scanf("%s", a[i].lastname);
printf("enter firstname:\n");
scanf("%s", a[i].firstname);
printf("enter address:\n");
scanf("%s", a[i].address);
printf("enter phone number:\n");
scanf("%s", a[i].phonenumber);
fp = fopen("addressbook.dat","a+");
fwrite(&a, sizeof(a), 1, fp);
fclose(fp);
}
for(i=0; i<5; i++)
{
fopen("addressbook.dat", "r");
fread(&a, sizeof(a), 1, fp );
printf("lastname:%s\n", a[i].lastname);
printf("firstname:%s\n", a[i].firstname);
printf("address:%s\n", a[i].address);
printf("phonenumber:%s\n", a[i].phonenumber);
fclose(fp);
}
return 0;
}
i am not getting any output. it was blank.
Check out this code, and let me explain you what all was wrong in your code.
#include<stdio.h>
typedef struct
{
int select;
char lastname[25];
char firstname[25];
char address[25];
char phonenumber[25];
} addressbook;
#define ARRAYLEN 2
addressbook a[ARRAYLEN];
FILE *fp;
int main()
{
int i;
fp = fopen("addressbook.dat","a+");
for( i=0; i<ARRAYLEN ; i++)
{
printf("enter details\n");
printf("enter lastname:\n");
scanf("%s", a[i].lastname);
printf("enter firstname:\n");
scanf("%s", a[i].firstname);
printf("enter address:\n");
scanf("%s", a[i].address);
printf("enter phone number:\n");
scanf("%s", a[i].phonenumber);
fwrite(&a[i], sizeof(a), 1, fp); /* notice, array indexed */
}
fclose(fp);
fopen("addressbook.dat", "r");
for(i=0; i<ARRAYLEN; i++)
{
fread(&a[i], sizeof(a), 1, fp );
printf("lastname:%s\n", a[i].lastname);
printf("firstname:%s\n", a[i].firstname);
printf("address:%s\n", a[i].address);
printf("phonenumber:%s\n", a[i].phonenumber);
}
fclose(fp);
return 0;
}
Actually, your code as-is (apart from the edit you've already done) isn't so incorrect, but it had some small yet crucial flaws.
The only real change is this :-
fwrite(&a[i],...
and,
fread(&a[i],...
i.e. pass the address of the particular array-element that you want to write, not the entire array. Also, even though you were passing address of the entire array, the no. of byte/characters you were asking library to write, was just sizeof(thestructure), so essentially the remaining was truncated. Without that, what you were writing into the file was something like...
A <-- file contents after, first iteration
AAB <-- file contents after, second iteration
AABABC <-- file contents after, third iteration
AABABCABCD <-- file contents after, fourth iteration
....
I think you'd figure out from that, what was wrong. Also the contents of your addressbook.dat was text, so a simple "cat addressbook.dat" (on Linux) would have told you what was wrong :-)
You are opening and closing file in every iteration. Now this is not an error, but just a sub-optimal thing, and quite likely to be something you do not want to do. File operations are costly, and opening/closing those cost quite a few CPU cycles. You are better off, opening file once for all writes, and once for reads. (Of course, once can remove the fclose() done after write-block and fopen() done before read-block as well, by just getting the file-pointer to the beginning of file -- left as an exercise for you).
While testing, no one wants to enter so much data. So I've added a #define (and with a newer compiler you can replace it with a const definition as well), that defines a macro which holds the addressbook array size. For testing, I keep it at "2". For production you can just change that value to "1000" and it will still work. Again, this wasn't an error, just a better style, if you will.
Oh, and BTW, pls get your indentation right. Are you coming from Python world ? Or it could be an artifact of the indentation required by SO for posting code-blocks.
HTH
It seems to me that you are not including the required headers. For example, printf requires stdio.h, so at the beginning for your file, you will need
#include <stdio.h>
CPlusPlus.com provides pretty good and easy to search documentation for C, so if you wish to use a function, you can look it up and find out which header is required.

Resources