Why is the file not opening using fopen? - c

I have tried several methods but none of them have worked.
I copied the txt file into the root file and it didn't open too. I have also tried to use the full path of the txt file. The same thing happened when I tried to use another IDE on another laptop.
Also the compiler isn't giving me any error.
Here is my code:
int main()
{
struct TreeNode *tmpDicNode;
struct LinkedList *tmpLinkedList;
FILE *infile;
infile = fopen("..//Synonyms.txt" ,"r");
char line[500];
while(fgets(line, 500, infile))
{
//if ( strlen(line)>0){
line[strlen(line) - 2] = '\0';
char * token = strtok(line, " -\n");
tmpDicNode = newTreeNode(token);
tmpLinkedList = newLinkedList();
while(token != NULL )
{
token = strtok(NULL, " , -\n");
if (token != NULL)
{
insertSynonym(tmpLinkedList, token);
}
}
tmpDicNode->synonyms = tmpLinkedList;
Root = insertWord(Root, tmpDicNode);
}
fclose(infile);
int ch = 0;
char userWord[30];
char userWord2[30];
while(ch!=8)
{
printf("\n=====================================\n");
printf("1. View The Dictionary.\n");
printf("2. test word existence.\n3. print synonyms of a word.\n");
printf("4. add a synonym to a word.\n5. get the biggest word with synonyms.\n");
printf("6. get all words of a synonym.\n");
printf("7. Save the dictionary to dict.txt file.\n");
printf("8. Exit.\n");
printf("=====================================\n");
printf("\nEnter Your Choice: ");
scanf("%d",&ch);
switch (ch)
{
case 1:
viewDictionary(Root);
break;
case 2:
printf("Enter word: ");
scanf("%s", userWord);
if (findWordNode(userWord)) printf("%s is present in the dict \n", userWord);
else printf("%s isn't found! \n", userWord);
break;
case 3:
printf("Enter word: ");
scanf("%s", userWord);
printLinkedlist(findWordNode(userWord)->synonyms);
break;
case 4:
printf("Enter word: ");
scanf("%s", userWord);
printf("Enter synonym: ");
scanf("%s", userWord2);
AddToWordSynonyms(userWord, userWord2);
break;
case 5:
printf("The word with the height no. of Synonyms is: %s", getMaxSynsWord(Root)->word);
break;
case 6:
printf("Enter a synonym: ");
scanf("%s", userWord);
getSyncWords(Root, userWord);
break;
case 7:
saveTheDictToFile(Root);
printf("The dictionary saved to others/dict.txt, Go and check it!\nGoodbye..!\n");
ch = 8;
break;
case 8:
printf("Goodbye..!\n");
break;
default:
printf("Please Enter a valid option number from 1 to 7\n");
}
}
return 0;
}

Let's address a couple of the issues here:
synonyms.txt
cold: cool,frigid,freezing
good: acceptable,virtuous
readsyn.c
/*
* readsyn.c
*
* SAMPLE OUTPUT:
* Current directory: C:\Users\paulsm\workspace-cdt\readsyn\Debug
* Opening file (..\synonyms.txt)
* Reading file (..\synonyms.txt)
* line=cold: cool,frigid,freezing
* ...
* Currently 4 words
* line=good: acceptable,virtuous...
* Currently 7 words
* Done: found 2 lines
* synonyms[0]:cold synonyms[1]:cool synonyms[2]:frigid synonyms[3]:freezing synonyms[4]:good synonyms[5]:acceptable synonyms[6]:virtuous
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MAXWORDS 10
#define MAXLINE 80
#define TOKENS ":,"
#define FNAME "..\\synonyms.txt"
int main(int argc, char *argv[])
{
char synonyms[MAXWORDS][MAXLINE] = {0};
char current_folder[MAXLINE];
char line[MAXLINE], *token;
FILE *infile;
int nlines = 0, iword=0;
printf ("Current directory: %s\n", getcwd(current_folder, MAXLINE));
printf ("Opening file (%s)\n", FNAME);
if (!(infile = fopen(FNAME,"r"))) {
perror("File open failed");
return 1;
}
printf ("Reading file (%s)\n", FNAME);
while((fgets(line, MAXLINE, infile) != NULL) && (iword < MAXWORDS))
{
printf("line=%s...\n", line);
if (line[strlen(line)-1] == '\n')
line[strlen(line)-1] = 0;
token = strtok(line, TOKENS);
while (token != NULL) {
strncpy (synonyms[iword], token, MAXLINE);
token = strtok(NULL, TOKENS);
iword++;
}
printf("Currently %d words\n", iword);
nlines++;
}
fclose(infile);
printf ("Done: found %d lines\n", nlines);
for (int i=0; i < iword; i++)
printf ("synonyms[%d]:%s ", i, synonyms[i]);
return 0;
}
Main points:
ALWAYS check if an I/O operation like "fopen()" succeeded or failed.
You can use APIs like getcwd() (among others) to get your current working directory.
If — as in your example — you don't give an absolute path (like "C:\\temp\\f.txt" on Windows, or "/tmp/f.txt" on *nix) for your filename, then the path argument is interpreted relative to that current working directory of the application. In Visual Studio that is by default somewhere buried in the Debug directory of your project; in Linux it would be the current directory of your shell.

Related

Create a file and write struct with data member and the file created is empty

I create a program that prompts the user to choose an option, like below:
create a file and name the file.
add component in the file
display the item in the file
exit program
So my problem is the file is created and exists in my directory, but it is empty, so where did I miss something? plus can you check whether the 2 and 3 option program are OK?
Here my program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num, name;
start:
printf("\n1. Create a file.");
printf("\n2. Add a component to the list.");
printf("\n3. Display the current list of component.");
printf("\n4. Exit program.");
printf("\n\nChoose either these four menu = ");
scanf("%d", &num);
fflush(stdin);
switch (num) {
case 1:
printf("\n\nPlease enter file name: ");
scanf("%d", &name);
FILE *pf = NULL;
char username[250];
char userfile[255];
printf("username: ");
scanf("%s", username);
sprintf(userfile, "%s.txt", username);
fflush(stdin);
goto start;
break;
case 2:
pf = fopen(userfile, "w");
if (!pf) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
struct date {
int day;
int month;
int year;
};
struct details {
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n, i;
printf("Enter number of items:");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++) {
fflush(stdin);
printf("Item name: \n");
scanf("%s", item[i].name);
fflush(stdin);
printf("Item code: \n");
scanf("%d", &item[i].code);
fflush(stdin);
printf("Quantity: \n");
scanf("%d", &item[i].qty);
fflush(stdin);
printf("price: \n");
scanf("%d", &item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy): \n");
scanf("%d-%d-%d", &item[i].mfg.day,
&item[i].mfg.month, &item[i].mfg.year);
}
fclose(pf);
goto start;
break;
case 3:
pf = fopen(userfile, "r");
if (!userfile) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
{
printf(" ***** INVENTORY ***** \n");
printf("------------------------------------------------------------------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE | MFG.DATE \n");
printf("-------------------------------------------------------- ---------\n");
for (i = 0; i < n; i++)
fprintf("%d %-15s %-d %-5d %-5d %d/%d/%d \n",
i + 1, item[i].name, item[i].code, item[i].qty,
item[i].price, item[i].mfg.day, item[i].mfg.month,
item[i].mfg.year);
printf("------------------------------------------------------------------\n");
}
fclose(pf);
goto start;
break;
case 4:
printf("Exit Program, Thank You, Sayonara");
break;
}
return 0;
}
There are multiple problems in your code:
the test if (!userfile) is incorrect: you should test if (!pf) instead
you open the file for reading, you should open it for writing with "w", or possibly for appending with "a".
you never write to the file. You should use fprintf(pf, ...) instead of printf.
the arrays userfile, item and variables i and n are local inside the switch statement: their contents go out of scope when you go to the start label outside de switch statement. Move all these definitions outside the switch statement.
fflush(stdin); has undefined behavior. You can consume (flush) the rest of the input line with: int c; while ((c = getchar()) != EOF && c != '\n') continue; You can define a function flush() that does it.

Reading function in C with structure and txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Can someone help me write a function to read from a .txt file. I made all of this, and I wrote a lot of different functions to read from file, but none of them worked. Every time I pressed option 2, it didn't show me what I wrote to file. Code works without errors, I am just out of ideas how to write a reading function.
Header.h
#ifndef HEADER_H
#define HEADER_H
typedef struct tenant {
char fname[30];
char lname[30];
int floor;
int phone;
}TENANT;
void write(FILE*, int, TENANT*);
#endif
Source.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include "Header.h"
#include <iostream>
#include <conio.h>
int main() {
int n = 0, helper = 0;
char nameFile[100];
TENANT *tenant = NULL;
tenant = (TENANT*)calloc(200, sizeof(TENANT));
FILE *file = NULL;
printf("Name of building: ");
scanf("%s", nameFile);
printf("\n");
while (n != 4) {
printf("Press 1 for creating file! \n");
printf("Press 2 for reading from file! \n");
printf("Press 3 for adding new tenants! \n");
printf("Press 4 to close the file! \n\n");
printf("Number: ");
scanf("%d", &n);
printf("\n");
switch (n)
{
case 1:
file = fopen(nameFile, "w");
printf("File created.\n");
printf("\n");
fclose(file);
break;
case 2:
if ((file = fopen(nameFile, "r")) == NULL)
{
printf("File is not yet created!\n\n");
break;
}
else
{
file = fopen(nameFile, "r");
read(file, helper, tenant);
printf("\n");
fclose(file);
}
break;
case 3:
helper++;
printf("Insert details of tenant: \n", helper);
file = fopen(nameFile, "a");
write(file, helper, tenant);
printf("\n");
fclose(file);
break;
case 4:
printf("Program closed!\n");
break;
default:
break;
}
}
free(tenant);
system("PAUSE");
return 0;
}
Functions.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "Header.h"
void write(FILE* file, int helper, TENANT* tenant) {
int i = helper - 1;
printf("Name of tenant: ");
scanf("%s", (tenant + i)->fname);
printf("Laste name of tenant: ");
scanf("%s", (tenant + i)->lname);
printf("Floor: ");
scanf("%d", &(tenant + i)->floor);
printf("Phone: ");
scanf("%d", &(tenant + i)->phone);
fprintf(file, "Name: %s\nLast name: %s\nFloor: %d\nPhone: 0%d\n", (tenant + i)->fname, (tenant + i)->lname, (tenant + i)->floor, (tenant + i)->phone);
fprintf(file, "\n//////////////////////////////////////////////////////////////////////////\n");
}
void read(FILE* file, int helper, TENANT* tenant)
{
fread(tenant, sizeof(*tenant), 1, file);
for (int i = 0; i < helper; i++)
{
fscanf(file, "Name: %s\nLast name: %s\nFloor: %d\nPhone: 0%d\n", (tenant + i)->fname, (tenant + i)->lname, (tenant + i)->floor, (tenant + i)->phone);
}
}
I think you should not name your function write() because there is system call named write(), see man 2 write. Same for read.
There are some bugs you should be aware of, maybe compile your code with -Wall so you can see.
There is no %d in your format for printf() function, yet you passed it variable helper.
printf("Insert details of tenant: \n", helper);
In your read() function you dont need this line of code
fread(tenant, sizeof(*tenant), 1, file);
There are many problems with this. You shoud read man 3 fread to see how it works.
So, just make your read function like this
void read(FILE* file, int helper, TENANT* tenant)
{
for (int i = 0; i < helper; i++)
{
fscanf(file, "Name: %s\nLast name: %s\nFloor: %d\nPhone: 0%d\n", (tenant + i)->fname, (tenant + i)->lname, (tenant + i)->floor, (tenant + i)->phone);
}
}
In your main program i think you will have problems with variable helper.
You initialized it in main function like this
int helper=0;
So first time you call write function you will pass variable helper with value 0, and inside of function your indexer i will start from -1. This will cause index out of range and undefined program behaviour.
Maybe you should initialize helper to be 1 from the start.
After every call to read or write function increment helper so you will not overwrite tenant[0].
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct tenant {
char fname[30];
char lname[30];
int floor;
int phone;
}TENANT;
void write(FILE* file, int helper, TENANT* tenant) {
int i = helper - 1;
printf("Name of tenant: ");
scanf("%s", (tenant + i)->fname);
printf("Laste name of tenant: ");
scanf("%s", (tenant + i)->lname);
printf("Floor: ");
scanf("%d", &(tenant + i)->floor);
printf("Phone: ");
scanf("%d", &(tenant + i)->phone);
fprintf(file, "Name: %s\nLast name: %s\nFloor: %d\nPhone: 0%d\n", (tenant + i)->fname, (tenant + i)->lname, (tenant + i)->floor, (tenant + i)->phone);
fprintf(file, "\n//////////////////////////////////////////////////////////////////////////\n");
}
void read(FILE* file, int helper, TENANT* tenant)
{
for (int i = 0; i < helper; i++)
{
fscanf(file, "Name: %s\nLast name: %s\nFloor: %d\nPhone: 0%d\n", (tenant + i)->fname, (tenant + i)->lname, &((tenant + i)->floor), &((tenant + i)->phone));
}
}
int main() {
int n = 0, helper = 1;
char nameFile[100];
TENANT *tenant = NULL;
tenant = (TENANT*)calloc(200, sizeof(TENANT));
FILE *file = NULL;
printf("Name of building: ");
scanf("%s", nameFile);
printf("\n");
while (n != 4) {
printf("Press 1 for creating file! \n");
printf("Press 2 for reading from file! \n");
printf("Press 3 for adding new tenants! \n");
printf("Press 4 to close the file! \n\n");
printf("Number: ");
scanf("%d", &n);
printf("\n");
switch (n)
{
case 1:
file = fopen(nameFile, "w");
printf("File created.\n");
printf("\n");
fclose(file);
break;
case 2:
if ((file = fopen(nameFile, "r")) == NULL)
{
printf("File is not yet created!\n\n");
break;
}
else
{
printf("read");
read(file, helper++, tenant);
//after you test your program for reading
//just delete fprintf :)
fprintf(stdout, "Name: %s\nLast name: %s\nFloor: %d\nPhone: 0%d\n", tenant[0].fname, tenant[0].lname, tenant[0].floor, tenant[0].phone);
printf("\n");
fclose(file);
}
break;
case 3:
helper++;
printf("Insert details of tenant: \n");
file = fopen(nameFile, "a");
write(file, helper, tenant);
printf("\n");
fclose(file);
break;
case 4:
printf("Program closed!\n");
break;
default:
break;
}
}
free(tenant);
system("PAUSE");
return 0;
}
Be aware you are using variable helper for reading and for writing. Maybe use different variables for this because you wont read from the start of the file if you increment your variable helper while writing in it :)

Program is not reading some characters from first line of text file

So my program basically asks for the assignment name/student name after clicking "1" from the student menu to submit an assignment. The function reads an arbitrary assignment from a text file I have in my debug folder, called "myassignment.txt". Then it creates a new file called "submission.txt" with the assignment name, student name and the assignment in it.
When I click "2" from the student menu to see the submitted assignment, it prints the assignment name and student name fine, but skips the first few characters from the first line of the actual assignment.
It skips more or less characters depending on how long the assignment name and student name are.
I can't figure out why it's doing this.
Here is my code for the data structure, menu, and functions used in the first two options of the menu:
#include "assignmentgrading3.h"
#define MAX_STUDENT_NAME_SIZE 50
#define MAX_ASSIGNMENT_NAME_SIZE 50
#define MAX_ASSIGNMENT_SIZE 1000
typedef struct{
char assignmentName[MAX_ASSIGNMENT_NAME_SIZE];
char studentName[MAX_STUDENT_NAME_SIZE];
char assignment[MAX_ASSIGNMENT_SIZE];
double score;
} Assignment;
void studentMenu(Assignment* assignmentStruct) {
int choice;
do {
printf("\nStudent Menu:\n");
printf("1. Submit an assignment\n");
printf("2. See the submitted assignment\n");
printf("3. See the graded assignment\n");
printf("4. Exit\n");
printf("Please enter a number from 1 - 4: ");
scanf("%d", &choice);
switch (choice) {
case 1:
submitAssignment(assignmentStruct, "myassignment.txt");
break;
case 2:
getAssignment(assignmentStruct);
displayAssignment(assignmentStruct);
break;
case 3:
getGradedAssignment(assignmentStruct);
displayGradedAssignment(assignmentStruct);
break;
case 4:
exit(0);
break;
}
} while (choice != 5);
}
void readRemainingLines(FILE* pFile, char* assignment){
long charsRead = 0;
while(fgets(assignment + charsRead, MAX_ASSIGNMENT_SIZE - charsRead, pFile)!= NULL)
{
charsRead = strlen(assignment);
if(charsRead >= MAX_ASSIGNMENT_SIZE - 1) //Credits: Carl Gelfand
break;
}
assignment[MAX_ASSIGNMENT_SIZE-1] = 0; //Just to make sure.
}
//Reads the file whose name is provided as string “fileName”,
//and creates a file named “submission.txt” as specified in the functional specification.
//It returns a 1 when it is successful, otherwise it returns a 0.
int submitAssignment(Assignment* assignmentStruct, char* fileName) {
FILE* pFile =0;
//char assignment[MAX_ASSIGNMENT_SIZE];
char* submissionFileName="submission.txt";
//Reading information from a user provided file : fileName
pFile = fopen(fileName,"r");
if(pFile==NULL){
printf("%s file did not open\n,",fileName);
exit(0);
}//EO if(pFile==NULL)
printf("Please enter the name of the assignment: ");
scanf(" %s", assignmentStruct->assignmentName);
printf("Please enter your (student) name: ");
scanf(" %s", assignmentStruct->studentName);
readRemainingLines(pFile, assignmentStruct->assignment);
fclose(pFile);
// Writing Information to "submission.txt"
pFile = fopen(submissionFileName, "w");
if(pFile == NULL) {
printf("%s file did not open\n,", submissionFileName);
exit(0);
} //EO if(pFile==NULL)
fprintf(pFile, "%s\n", assignmentStruct->assignmentName);
fprintf(pFile, "%s\n", assignmentStruct->studentName);
fprintf(pFile, "%s\n", assignmentStruct->assignment);
fclose(pFile);
return 1;
}
int getAssignment(Assignment* assignmentStruct) {
FILE* pFile = 0;
pFile = fopen("submission.txt","r");
if(pFile==NULL){
printf("file did not open\n,");
exit(0);
}
fscanf(pFile, "%[^\n]", assignmentStruct->assignmentName);
fscanf(pFile, "%[^\n]", assignmentStruct->studentName);
readRemainingLines(pFile, assignmentStruct->assignment);
return 1;
}
void displayAssignment(Assignment* assignmentStruct) {
char* middleOfAssignment = &(assignmentStruct->assignment[strlen(assignmentStruct->assignmentName) + strlen(assignmentStruct->studentName) + 2]);
print(assignmentStruct->assignmentName, assignmentStruct->studentName);
printf("%s \n", middleOfAssignment);
//printf("%s \n", assignment);
}
void print(char* assignmentName, char* studentName) {
printf("Assignment Name: %s \nStudent: %s\n", assignmentName, studentName);
}
displayAssignment is skipping over the first few characters of the assignment when it assigns middleOfAssignment. It's skipping the first strlen(assignmentStruct->assignmentName) + strlen(assignmentStruct->studentName) + 2 characters.
It should just print assignmentStruct->assignment, there's no need for middleOfAssignment. The only reason for that code would be if assignment contained a copy of the assignment name and student name at the beginning, but it doesn't.
void displayAssignment(Assignment* assignmentStruct) {
print(assignmentStruct->assignmentName, assignmentStruct->studentName);
printf("%s \n", assignmentStruct->assignment);
}

Reading a binary file and show the entries [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I may need your help to solve this issue...
I'm learning about C and find a problem, how to properly read a binary file.
I have a struct array filled, then wrote on binary file and try to read it, but this isn't show nothing.
The code is in pastebin
My code
#include <stdio.h>
#include <ctype.h>
#include <math.h>
typedef struct {
int id;
char name[100];
char document[14];
float testGrade;
} Candidate;
typedef struct {
int id;
float testGrade;
} Grade;
FILE * openFile(char filename[100], char filemode[3]) {
FILE *p = fopen(filename, filemode);
if (!p) {
printf("Error to open %s file. \nThe program will be closed.",filename);
exit(1);
}
}
void addCandidate(int newId, int numbersOfNewCandidate, char candidateFilename[100], char gradeFilename[100]) {
int counter = 0;
float testGrade = 0;
Candidate*candidate;
candidate= malloc(sizeof(Candidate) * numbersOfNewCandidate);
Grade *grade;
grade= malloc(sizeof(Grade) * numbersOfNewCandidate);
for(;counter< numbersOfNewCandidate; counter++) {
system("#cls||clear");
printf("Adding #%d:",newId);
printf("\n---------------\n");
printf("\nName of candidate: ");
gets(&candidate[counter].name);
printf("\nDocument: ");
gets(&candidate[counter].document);
do {
printf("\nTest grade (between 0 and 10): ");
scanf("%f",&testGrade);
printf("\n---------------\n");
if (testGrade < 0 || testGrade > 10) {
printf("\nERROR!\nTest grade %.2f invalid, please try again with a grade between 0 and 10.\n",testGrade);
}
} while(testGrade < 0 || testGrade > 10);
candidate[counter].id = newId;
grade[counter].id = newId;
candidate[counter].testGrade = testGrade;
grade[counter].testGrate = testGrade;
newId++;
fflush(stdin);
}
FILE *candidateFile = openFile(candidateFilename, "a+b");
fwrite(candidate, sizeof(candidate),numbersOfNewCandidate, candidateFile );
FILE *gradeFile = openFile(gradeFilename, "a+b");
fwrite(grade, sizeof(grade),numbersOfNewCandidate, gradeFile );
fclose(candidateFile);
fclose(gradeFile);
free(candidate);
free(grade);
}
void showCandidate(int typeOfSearch, char valueToSearch[100]) {}
void listAllCandidates(char candid[100]) {
FILE *fp = openFile(candidateFilename, "rb");
//fseek(fp,0,SEEK_SET);
Candidate *candidate = NULL;
candidate = malloc(sizeof(Candidate) + 1);
while(fread(&candidate,sizeof(Candidate),1,fp) == 1) {
printf("\n\nId: %d \nName: %s \nDocument: %s \nGrade: %.2f",candidate->id,candidate->name,candidate->document, candidate->testGrade);
}
getche();
free(candidate);
}
void main(){
int lastId = 0;
char candidateFilename[100] = "candidates.bin";
char gradeFilename[100] = "classificationList.bin";
char option;
do {
system("#cls||clear");
printf("Menu: \n");
printf("1 - Add candidates \n");
// printf("2 - Search by name \n");
// printf("3 - Search by document \n");
// printf("---------------------------\n");
// printf("4 - Show Max Grade, Minimum, Avg \n");
printf("5 - List candidates \n");
printf("6 - Erase files \n");
printf("---------------------------\n");
printf("S - Exit \n");
printf("\n\n");
option = toupper(getche());
switch(option) {
case '1':
system("#cls||clear");
int numbersOfNewCandidate = 0;
int newId = 0;
printf("Home > Add candidates\n\n");
printf("Please give the number of new candidates: ");
scanf("%d",&numbersOfNewCandidate);
newId = lastId;
lastId += numbersOfNewCandidate;
fflush(stdin);
addCandidate(newId + 1, numbersOfNewCandidate, candidateFilename, gradeFilename);
printf("\n\nAdding new candidates: Finished \n");
break;
// case '2':
// printf("\noption %c#\n",option);
// break;
// case '3':
// printf("\noption %c#\n",option);
// break;
// case '4':
// printf("\noption %c?\n",option);
// break;
case '5':
listAllCandidates(candidateFilename);
break;
case '6':
remove(candidateFilename);
remove(gradeFilename);
printf("\nRemoved!!\n");
break;
case 'S':
printf("\noption %c, the program will be ended...\n",option);
break;
default:
printf("\nWrong option!!\n");
break;
}
} while (option != 'S');
}
Please, if you find other issues about my code, try to elucidate me about it..
I already tryed it too, but nothing yet.
while(!feof(fp)) {
fread(&candidate,sizeof(Candidate),1,fp);
printf("\n\nId: %d \nName: %s \nDocument: %s \nGrade: %.2f",candidate->id,candidate->name,candidate->document, candidate->testGrade);
}
Candidate *candidate = NULL;
candidate = malloc(sizeof(Candidate) + 1);
while(fread(&candidate,sizeof(Candidate),1,fp) == 1) {...}
free(candidate);
The first parameter in fread should be a pointer fread(void*,...), and candidate is already declared as a pointer, it should not have a reference operator. The correct usage is:
while(fread(candidate,sizeof(Candidate),1,fp) == 1) {...}
Note that there is no reference & operator in front of candidate
Sometime you see a reference operator, but that's a different case like this:
Candidate cand;
while(fread(&cand,sizeof(cand),1,fp) == 1) {...}
This is an easier method because cand does not need to be allocated with malloc and it does not need free
Unnecessary functions introduce more errors:
FILE * openFile(char filename[100], char filemode[3]) {
FILE *p = fopen(filename, filemode);
if (!p) {
printf("Error to open %s file. \nThe program will be closed.",filename);
exit(1);
}
}
This function is supposed to return a file pointer. Also function parameter can be simply written as const char* filename and const char *filemode. Example:
FILE * openFile(const char* filename, const char* filemode) {
FILE *p = fopen(filename, filemode);
if (!p) printf("Error to open %s file. \nThe program will be closed.",filename);
return p;
}
I would get rid of this function altogether because it's basically useless. Just use fopen. Make sure to close the handle with fclose when you are done.
grade[counter].testGrate = testGrade;
^
This is a typo, it should be grade[counter].testGrade. It is recommended to compile the program with warning level set to maximum, or at least set to level 4. The compiler will tell about about the typos, errors and warnings. You have to be able to compile the program with zero errors and zero warnings. Here is a simple version:
void listAllCandidates(char* candidateFilename)
{
FILE *fin = fopen(candidateFilename, "rb");
Candidate cand;
while(fread(&cand, sizeof(cand), 1, fin))
printf("%s, %s, %d, %f\n", cand.name, cand.document, cand.id, cand.testGrade);
fclose(fin);
}
int main()
{
char candidateFilename[] = "file.bin";
FILE *fout = fopen(candidateFilename, "ab");
Candidate cand;
strcpy(cand.name, "name1");
strcpy(cand.document, "document1");
cand.id = 1;
cand.testGrade = 1.1f;
fwrite(&cand, sizeof(cand), 1, fout);
strcpy(cand.name, "name2");
strcpy(cand.document, "document2");
cand.id = 2;
cand.testGrade = 2.2f;
fwrite(&cand, sizeof(cand), 1, fout);
fclose(fout);
listAllCandidates(candidateFilename);
printf("\n");
return 0;
}

How do I open a binary file using a string? Using C

I was under the impression that to open binary files using strings, you could simply create the string, and then implement it as the name of the file where it will read the string. This is what my lecture notes state. However I'm obveously missing something. I've used &name, name, &name[SIZE] within the fopen and each time i've gotten inBinFile == NULL unless I use the commented line. My string is correct. What's wrong? Help is much appreciated. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 25
int frstmenu(void);
int sndmenu(void);
int main()
{
int fmenu, smenu;
char name[SIZE];
FILE *inBinFile;
unsigned char numRead;
fmenu = frstmenu();
if ( fmenu !=1 && fmenu !=2 )
{
printf("\nIncorrect option\n");
fmenu = frstmenu();
}
if (fmenu == 1)
{
printf("\nEnter the file name: \n");
scanf("%s", &name[SIZE]);
/* printf("filename: %s", &name[SIZE]); */
smenu = sndmenu();
if (smenu !=1 && smenu !=2 )
{
printf("\nIncorrect option\n");
smenu = sndmenu();
}
if (smenu == 1)
{
inBinFile = fopen( name, "rb");
/* inBinFile = fopen( "stream.grc", "rb"); */
if (inBinFile == NULL)
{
fprintf(stderr, "Error opening %s", &name[SIZE]);
return(-1);
fclose(inBinFile);
}
}
return(0);
}
int frstmenu()
{
float selection;
printf("----Menu----\n");
printf("1 Open a file ( supported format: .grc )\n");
printf("2 Exit the program\n");
printf(" Please select an option (1 or 2): ");
scanf("%f", &selection);
return(selection);
}
int sndmenu()
{
int selection;
printf("---Menu---\n");
printf("1 Decode the sequence\n");
printf("2 Exit the program\n");
printf(" Please select an option (1 or 2):\n");
scanf("%i", &selection);
return(selection);
}
You probably want to say
scanf("%s", &name[0]);
or even just:
scanf("%s", name);
Your &name[SIZE] points to name + SIZE, which is beyond the allocated memory.

Resources