File Reading in C returns empty - c

I'm able to write data into a file but when I read it, it prints an empty file. I tried to make 2 programs one to write to file using permission "w" and one to read using "r" but when I combined both programs and changed permission to "w+" printing the files gives lots of empty spaces.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char name[20];
char roll_no[15];
char class[10];
char semester[10];
char course[20];
FILE *file_pointer;
file_pointer = fopen("StudentRecords.txt", "w+");
if (file_pointer == NULL)
{
printf("\nError Opening File StudentRecords.txt\nCreate File Manually and Try Again.");
exit(1);
}
printf("\nENTER DETAILS FOR 5 STUDENTS\n");
//TAKE 5 RECORDS FROM USERS AND SAVE THEM IN FILE-
for (int i = 1; i <= 5; i++)
{
printf("\nStudent %d", i);
fprintf(file_pointer, "Student %d", i);
printf("\nName : ");
scanf("%s", &name);
fprintf(file_pointer, "\nName : %s", name);
printf("Roll No : ");
scanf("%s", &roll_no);
fprintf(file_pointer, "\nRoll No : %s", roll_no);
printf("Class : ");
scanf("%s", &class);
fprintf(file_pointer, "\nClass : %s", class);
printf("Semester : ");
scanf("%s", &semester);
fprintf(file_pointer, "\nSemester : %s", semester);
printf("Course : ");
scanf("%s", course);
fprintf(file_pointer, "\nCourse : %s", course);
printf("\n");
fprintf(file_pointer, "\n\n");
}
//READ ENTIRE FILE WORD BY WORD
char c;
c = fgetc(file_pointer);
while (c != EOF)
{
printf("%c", c);
c = fgetc(file_pointer);
}
fclose(file_pointer);
}

When you write/read in a file you use a stream (FILE*) that stores where in the file you are (position).
When you finished writting that was the last stream position.
You need to go back to the begin of the file if you want to read it entirely.
You can use fseek for this.
int fseek(FILE *stream, long int offset, int whence);
1 SEEK_SET : Beginning of file
2 SEEK_CUR : Current position of the file pointer
3 SEEK_END : End of file
...
//READ ENTIRE FILE WORD BY WORD
char c;
fseek(file_pointer, 0, SEEK_SET);
c = fgetc(file_pointer);
while (c != EOF)
{
printf("%c", c);
c = fgetc(file_pointer);
}

For the read section do this instead. This will reset the position indicator to the beginning of the file so you can read from the beginning.
if ( fseek(file_pointer, 0L, SEEK_SET) == 0 ) {
char c;
c = fgetc(file_pointer);
while (c != EOF)
{
printf("%c", c);
c = fgetc(file_pointer);
}
}

Related

write file to structs

I want to write and read some statics from file to structs.
write from structs to file is work of but write data from file isn't ok.
I will be grateful to help me what is the problem.
#include <stdio.h>
#include <stdlib.h>
const char* MemberFormatIn="(%[^,], %[^,], %[^,], %d)";
const char* MemberFormatOut="(%s, %s, %s, %d)\n";
typedef struct member {
char name[20],
lastName[20],
address[20];
int age;
}p1,p2;
void inputMemberList(struct member p[],int count) {
printf("name:");
scanf("%s",p[count].name);
printf("lastName:");
scanf("%s",p[count].lastName);
printf("address:");
scanf("%s",p[count].address);
printf("age:");
scanf("%d",&p[count].age);
}
void printMemberList(struct member p[],int count) {
system("cls");
for(int i=0; i<count; i++) {
printf("\aMember %d:\n", i+1);
printf("Name is: %s", p[i].name);
printf("\nLast name is: %s", p[i].lastName);
printf("\nAddress is: %s", p[i].address);
printf("\nAge is: %d", p[i].age);
printf("\n\n");
}
}
void saveMember(struct member p[],int count) {
FILE* fp = fopen("member.txt","a+");
if (fp == NULL) {
printf("File can't open.");
exit(1);
}
fprintf(fp, MemberFormatOut, p[count].name, p[count].lastName, p[count].address, p[count].age);
fclose(fp);
}
void fileToStructure(struct member p[],int count) {
FILE* fp = fopen("member.txt","a+");
if (fp == NULL) {
printf("File can't open.");
exit(1);
}
fseek(fp, 0, SEEK_SET);
for (int i=0; i<count+1; i++) {
fscanf(fp, MemberFormatIn, p[i].name, p[i].lastName, p[i].address, &p[i].age);
}
fclose(fp);
}
int numberOfMember() {
int count = 0;
char c;
FILE* fp = fopen("member.txt","r");
if(fp == NULL) {
printf("File can't open.");
exit(1);
}
do {
c = fgetc(fp);
if(c == '\n')
count++;
}while(c != EOF);
fclose(fp);
return count;
}
int main() {
int len = 100;
p1 p[len];
int count = numberOfMember();
inputMemberList(p,count);
saveMember(p,count);
fileToStructure(p,count);
printMemberList(p,count);
return 0;
}
at result just statics of member true and shown show but the others doesn't true.
File data(example):
(ahmad, dad, tir, 12)
(hossein, dad, tiran, 12)
(ali, dad, tir, 15)
(mohammadi, mmad, tiron, 16)
(helma, dad, tiran, 5)
(mohammad, amin, dadkhah, 5)
output(example):
Member 1:
Name is: ahmad
Last name is: dad
Address is: tir
Age is: 12
Member 2:
Name is: ├wöΩ\`
Last name is:
Address is: ↑
Age is: 0
Member 3:
Name is: Ä
Last name is: t
Address is: e
Age is: 7471221
Member 4:
Name is: r
Last name is: l
Address is: o
Age is: 6881396
Member 5:
Name is: n
Last name is: s
Address is:
Age is: 0
Member 6:
Name is:
Last name is:
Address is:
Age is: 0
In fileToStructure(), the first iteration of the loop calls fscanf() and if all is OK, the next character to be read from the file will be the newline character at the end of the first line. Unfortunately for the next iteration, the next call to fscanf() is expecting to read the ( character, but instead it reads the newline character. This will cause this call to fscanf() and all the subsequent calls to fail to match anything and return EOF.
The code needs to eat the newline character. One way to do that is to change the MemberFormatIn format string to one of the following:
const char* MemberFormatIn=" (%[^,], %[^,], %[^,], %d)"; - will discard any whitespace characters before the ( character; or
const char* MemberFormatIn="(%[^,], %[^,], %[^,], %d) "; - will discard any whitespace characters after the ) character.
The first one (discarding whitespace before the ( character) would be preferable for interactive input, but it doesn't matter too much when reading from a file.

How to write, read and delete a file in a single script in C programming

I created a file and filled it with some entries. However, I want to read this file and show it on the screen. Also, after showing the entries, I want it to be deleted with my permission. But I am stuck at this point please help me.
EDIT: Code is updated but still couldn't figure it out how to do :/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char name[20], surname[20], city[30], country[30], gender[15];
int count = 0;
int main() {
FILE *f1;
f1 = fopen("C:\\FurkanArslan.txt", "r+");
while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
printf("\n*Please enter required information: \n");
printf("Name :"); scanf("%s", name);
printf("Surname:"); scanf("%s", surname);
printf("Country:"); scanf("%s", country);
printf("City :"); scanf("%s", city);
printf("Gender :"); scanf("%s", gender);
fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
count++;
}
fclose(f1);
printf("\n<<<<<%d data has been successfully saved!>>>> \n", count * 5);
printf("-------------------------------------\n");
f1 = fopen("C:\\FurkanArslan.txt", "r");
char c, answer;
while ((c = fgetc(f1)) != EOF)
putchar(c); // In this part I displayed file on the screen.
printf("\n\n <<<< %d entries are displayed on the screen! >>>>", count * 5);
printf("\n\nWould you like to remove your file [Y/N] ?");
scanf(" %c", &answer);
if (answer == 'y' || answer == 'Y') {
remove("f1");
printf("\n\n***File successfully removed!");
}
return 0;
}
In order to show the content of a file you have to open it and read it letter by letter, after that, you can use the putchar function to output the current character
FILE *fp = fopen("path/to/file.txt","r");
char c;
while((c=fgetc(fp))!=EOF)
putchar(c);
fclose(fp);
after that to remove a file you need to use the remove function, which receives the name of the file as paramter.
remove("my_file.txt");
There are multiple issues in your code:
there is no need to make the variables and arrays global, just define them in the body of the main() function.
you should tell scanf() the maximum number of characters to store in the destination array with a length specifier in the format string (eg: "%19s") and check for conversion success.
the variable c used in the reading loop must have type int for proper detection of EOF. fgetc() returns a positive byte value if successful and the special negative value EOF at end of file.
you do not need to reopen the file after writing to it. Sine you opened it for update mode, you can just seek back to the beginning of the file with rewind(f1) or fseek(f1, 0L, SEEK_SET).
the file is open for read and update mode ("r+"): it will fail if the file does not exist. You should open it in write and update mode with "w+" to create or truncate it.
you should check that fopen succeeds at opening the file, otherwise you invoke undefined behavior passing a null stream pointer to fprintf.
to remove the file, remove() takes the filename as its argument. You must close the file before attempting to remove it.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *filename = "C:\\FurkanArslan.txt";
char name[20], surname[20], city[30], country[30], gender[15];
int count = 0;
FILE *f1 = fopen(filename, "w+");
if (f1 == NULL) {
printf("Cannot open file %s.\n", filename);
return 1;
}
while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
printf("\n*Please enter required information: \n");
printf("Name :"); if (scanf("%19s", name) != 1) break;
printf("Surname:"); if (scanf("%19s", surname) != 1) break;
printf("Country:"); if (scanf("%29s", country) != 1) break;
printf("City :"); if (scanf("%29s", city) != 1) break;
printf("Gender :"); if (scanf("%14s", gender) != 1) break;
fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
count++;
}
printf("\n<<<<< %d data has been successfully saved to %s! >>>>\n",
count * 5, filename);
printf("-------------------------------------\n");
rewind(f1);
int c;
while ((c = fgetc(f1)) != EOF)
putchar(c);
printf("\n\n <<<< %d entries are displayed on the screen! >>>>\n", count);
fclose(f1);
printf("\nWould you like to remove your file [Y/N] ?");
char answer;
if (scanf(" %c", &answer) == 1 && (answer == 'y' || answer == 'Y')) {
if (remove(filename)) {
printf("\n\n***Error removing file %s: %s\n",
filename, strerror(errno));
} else {
printf("\n\n***File %s successfully removed!\n", filename);
}
}
return 0;
}

Search and write data from one file to another

I need to write a C program to fetch data from one file and write it to another file, without using user defined functions. My requirements are to:
Search customer details by Name.
Store the transaction data (paid amount) in another text file.
I did the code to search by name. But its not working,
#include <stdio.h>
#include <stdlib.h>
int main () {
char name[10], nic[10], mobile[10];
char fname[10], fnic[10], fmobile[10];
char choice;
int amount;
FILE *cfptr;
printf("Enter search type - \n 1. NAME \n 2. NIC \n 3.MOBILE \n ----> ");
scanf("%c", &choice);
printf("Enter search text : ");
scanf("%s", &name);
cfptr = fopen ("customer.dat", "r");
while (!feof(cfptr)){
fscanf(cfptr, "%s %s %s", fname, fnic, fmobile);
printf("Read Name |%s|\n", fname );
printf("Read NIC |%s|\n", fnic );
printf("Read Mobile |%s|\n", fmobile );
}
fclose(cfptr);
scanf("%d", &amount);
return(0);
}
customer.dat File
Shan 100012 200202
Marsh 121213 667675
Kim 126573 663412
This code is not complete asI cant filter the single name assigning
if(name == fname)
as am getting
assignment to expression with array type error
Can any one complete me the code to search and save to another file so I can do the amount calculation part?
int Search_in_File(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];
//gcc users
//if((fp = fopen(fname, "r")) == NULL) {
// return(-1);
//}
//Visual Studio users
if((fopen_s(&fp, fname, "r")) != NULL) {
return(-1);
}
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
few comments:
when scanning the choice, read it as an integer and not as a character.
scanf("%c", &choice); // change to scanf("%d", &choice);
single '=' is an assigment, you meant comparison which is double '=='
if(name = fname) // comparison is if(name == fname)
in order to compare string, do not use '==' operator. use strcmp or implement an equivalent of strcmp.
Thanks for the effort, As with changes, I have changed my code as below and its working. Without checking with the name, I alternately checked with the nic.
#include <stdio.h>
int main(void){
int nic, n, mobile;
char name[30];
FILE *aPtr;
aPtr = fopen("Details.txt","w");
if(aPtr == NULL){
printf("File cannot be opened");
return -1;
}
printf("Enter nic to search - ");
scanf("%d", &n);
fscanf(aPtr, "%d %-s %d", &nic, name, &mobile);
while(!feof(aPtr)){
if(nic == n){
Printf("%d %s %d \n", nic, name, mobile);
}
fscanf(aPtr, "%d %s %d", &nic, name, &mobile);
}
fclose(aPtr);
return 0;
}

Separate Sections work correctly however when combined a crash is caused

The program works when the edit is alone and it also works when the read is alone :
printf("Enter the name of file you wish to edit:\n");
gets(file_name); //file_name = input
file = fopen(file_name,"w"); // write mode
if( file == NULL ) //If file couldn't be opened
{
perror("Error while opening the file!\n");
exit(EXIT_FAILURE);
}
printf("Enter name: \n"); scanf("%s",name1);
printf("Enter second name if applicable: \n"); scanf("%s",name2);
printf("Enter grade: \n"); scanf("%s",grade);
fprintf(file, "%s%s%s\t%s%s%s", name1, " ", name2, "=", " ", grade);
fclose(file);
printf("File write was successful\n");
And
printf("Enter the name of file you wish to see:\n");
gets(file_name); //file_name = input
file = fopen(file_name,"r"); // read mode
if( file == NULL ) //If file couldn't be opened
{
perror("Error while opening the file!\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while( ( character = fgetc(file) ) != EOF /*EOF = End Of File*/)
printf("%c",character); //print c (character)
fclose(file); //remove the file from RAM
However when they are put together with an if the program crashes as soon as 1 or 2 is inputted into the first section:
printf("Edit or Read file? (1 for edit, 2 or read)\n"); scanf("%s",RW);
Here is the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char character, file_name[25];
int RW;
const char *quit;
FILE *file; //"file" stores file stream
char data [100000];
char name1 [100000];
char name2 [100000];
char grade [100000];
printf("Edit or Read file? (1 for edit, 2 or read)\n"); scanf("%s",RW);
if (RW == 1)
{
printf("Enter the name of file you wish to see:\n");
gets(file_name); //file_name = input
file = fopen(file_name,"r"); // read mode
if( file == NULL ) //If file couldn't be opened
{
perror("Error while opening the file!\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while( ( character = fgetc(file) ) != EOF /*EOF = End Of File*/)
printf("%c",character); //print c (character)
fclose(file); //remove the file from RAM
} else if ( RW == 2) {
printf("Enter the name of file you wish to edit:\n");
gets(file_name); //file_name = input
file = fopen(file_name,"w"); // write mode
if( file == NULL ) //If file couldn't be opened
{
perror("Error while opening the file!\n");
exit(EXIT_FAILURE);
}
printf("Enter name: \n"); scanf("%s",name1);
printf("Enter second name if applicable: \n"); scanf("%s",name2);
printf("Enter grade: \n"); scanf("%s",grade);
fprintf(file, "%s%s%s\t%s%s%s", name1, " ", name2, "=", " ", grade);
fclose(file);
printf("File write was successful\n");
}
printf(" \n");
printf("Close window?\n"); scanf("%s",quit);
if (quit == "y")
{
printf("Bye!\n");
}
return (0);
}
the posted program crashes because of this line:
scanf("%s",RW);
the variable RW is declared as an int.
The call to scanf() is expecting a pointer to an char array.
so the code is trying to tread RW as a pointer, and followed that pointer (which contains what ever trash was on the stack at the location of RW. That is what is causing the crash.
Suggest writing the statement as:
scanf("%u",&RW);
As BLUEPIXY said:
scanf("%s",RW); --> scanf("%d%*c", &RW);
const char *quit; --> char quit; ... scanf("%s",quit); if(quit == "y") --> scanf(" %c", &quit); if(quit == 'y')
These changes meant that there were no problems with the variables.

Writing user input to a file in C programming

I am working on a program to write user input to a file and then search for a specific record in the file and output it to the screen.
I tried using fgets and also fputs, but I haven't been successful. Here's what I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
fileptr = fopen("C:\\Users\\Andrea\\Documents\\Tester.txt", "w");
if (fileptr == NULL) {
printf("File couldn't be opened\n\a\a");
fclose(fileptr);
exit(0);
}
printf("Enter name: \n");
fscanf(fileptr, "%c", name);
fputs(name, fileptr);
fclose(fileptr);
printf("File write was successful\n");
return 0;
}
Use:
fscanf(stdin, "%s", name);
But better still, use scanf instead, as kol mentioned. This is because scanf() is designed to read the user response from the screen while fscanf() is for scanning from any input streams (which are usually files).
And the statement should be reading from the screen (stdin), not from the file (which was opened as "write" only).
Use scanf to read user input, and fprintf to write it to the file. Then use fscanf to read from the file, and printf to display what you have read. See cplusplus.com for the details and sample code.
EDIT:
Here is an example (please run the executable from the command line):
#include <stdio.h>
#include <string.h>
int main()
{
FILE *file;
int i;
char firstName[32];
char lastName[32];
int found = 0;
// Open the file for writing
file = fopen("records.txt", "wt");
if (!file)
{
printf("File could not be opened\n\a\a");
getchar();
return -1;
}
// Read and save data
for (i = 0; i < 3; ++i)
{
// Read data
printf("Record #%d\n", i + 1);
printf("Enter first name: "); scanf("%s", firstName);
printf("Enter last name: "); scanf("%s", lastName);
printf("\n");
// Save data
fprintf(file, "%s\t%s\n", firstName, lastName);
}
// Close the file
fclose(file);
// Open the file for reading
file = fopen("records.txt", "rt");
if (!file)
{
printf("File could not be opened\n\a\a");
return -1;
}
// Load and display data
i = 0;
while(!feof(file) && !found)
{
++i;
fscanf(file, "%s\t%s", firstName, lastName);
if (strcmp(firstName, "John") == 0 && strcmp(lastName, "Doe") == 0)
{
printf("Record found (#%d): %s %s\n", i, firstName, lastName);
found = 1;
}
}
if (!found)
printf("Record could not be found");
// Close the file
fclose(file);
return 0;
}

Resources