Storage manager function to read block of a file - c

I am implementing a storage manager to open, create, read and write a file using file pointers and file handler. But i am not able to write efficient code to implement all of my read functions of my storage manager. The read function of my storage manager has to implement the following:
To read first block of a file
To read current block of a file
To read previous block of a file
To read next block of a file
To read last block of a file
Any suggestions and code examples would be helpful to me.
The following is the code written by me to read a data file using file pointer -
*/
#include
#include
void main()
{
FILE *fptr;
char filename[15];
char ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}

Related

fopen give me a segementation fault

I'm trying to open the output_voice_capture.txt but it gives me a segementation fault, not only the file exists but it has read privilege.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fPtr;
char ch;
/*
* Open file in r (read) mode.
*/
printf("Opening file ......\n");
fPtr = fopen("/flash/etc/output_voice_capture.txt", "r");
if(fPtr == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading file contents character by character.\n");
do
{ printf("Read single character from file ......\n");
/* Read single character from file */
ch = fgetc(fPtr);
/* Print character read code ASCII on console */
printf ("%d \n", ch);
} while(ch != EOF); /* Repeat this if last read character is not EOF */
printf("Closing file ......\n");
fclose(fPtr);
return 0;
}
I am using minicom which contains all the bin that I can use , the problem is that when I use linux terminal and a simple .txt test file the code works just fine.
As Zaboj Campula already said in his comment EOF is defined as an integer of -1. On some systems a char is a value from 0..255, on others from -127..128. To avoid any problems one should use the feof() function (link) to check the end of the stream. This might be the source of your problem due to the different sizes of char and int.
Your code will print "File opened successfully. Reading file contents character by character." for each character read.
Leave functions only at one place: at the end. This makes your code much more readable
When parts of your code depend on something, enclose it with an error check.
Try this code:
int main() {
FILE * fPtr;
char ch;
int result = 0;
printf("Opening file ......\n");
if (!(fPtr = fopen("/flash/etc/output_voice_capture.txt", "r")) {
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
result = EXIT_FAILURE;
} else {
printf("File opened successfully. Reading file contents character by character.\n");
while (EOF != (ch = fgetc(fPtr))) {
printf ("%d \n", ch);
}
fclose(fPtr);
}
return result;
}

File Pointer Not Being Assigned a Value When Using fopen()

I am trying to write a simple C program which will read data from a csv file and perform some calculations on this data.
Unfortunately I have a problem where a file pointer of mine, fptr , is not being assigned a value after calling fopen(). I know this is the case after stepping through VS 2017's debugger. Yet I do not know why this is the case. This is a huge problem and means my program will throw some very nasty exceptions any time I try to read data from the file or close the file.
My code is below:
main.c
#include<stdio.h>
#include <stdlib.h> // For exit() function
#include"constants.h" //For access to all project constants
/***************************************************************************************************************
To keep the terminal from automatically closing
Only useful for debugging/testing purposes
***************************************************************************************************************/
void preventTerminalClosure() {
//flushes the standard input
//(clears the input buffer)
while ((getchar()) != '\n');
printf("\n\nPress the ENTER key to close the terminal...\n");
getchar();
}
/***************************************************************************************************************
Read the given input file
***************************************************************************************************************/
void readInputFile(char fileName[]) {
FILE *fptr;
char output[255];
//open the file
if (fptr = fopen(fileName, "r") != NULL) { //read file if file exists
//fscanf(fptr, "%[^\n]", output);
//printf("Data from the file:\n%s", output);
printf("<--Here-->");
}else {
printf("\nERROR 1: File %s not found\n", fileName);
preventTerminalClosure();
exit(1);
}
fclose(fptr); //close the file
}
/***************************************************************************************************************
* * * Main * * *
***************************************************************************************************************/
void main() {
char testName[MAX_NAME_SIZE];
printf("Hello World!\n");
printf("Please enter your name: ");
scanf("%s", testName);
printf("It's nice to meet you %s!", testName);
readInputFile("dummy.txt");
preventTerminalClosure(); //Debug only
}
I have made sure that my fake file does indeed exist and is located in the correct location. Otherwise my code would hit the else block inside of readInputFile(). That is something I have thoroughly tested.
There is clearly something basic that I am missing which explains this pointer behavior; but what that is, I am not sure. Any help would be appreciated! :)
Use parenthesis to enforce order, so that fptr is compared against NULL after it has been assigned value returned by fopen:
FILE *fptr;
char output[255];
//open the file
if ( (fptr = fopen(fileName, "r")) != NULL)

need help My Library project has member problem

seems something is wrong. I've made a library project but some functions seem to be malfunctioning
for example : When i choose my member list (Shown below) it exists the code.
in c version.
void addmember()
{
system("cls");
// creating a FILE variable
FILE *fptr;
// creating a character variable
char ch;
// open the file in write mode
fptr = fopen("username.txt", "w");
// take user input
printf("Enter your name: ");
ch = getchar();
printf("Save any more?(Y / N):");
if(getch()=='n')
mainmenu();
else
system("cls");
addmember();
}
void memberlist(){
char ch;
FILE *fptr;
// open the file in read mode
fptr=fopen("username.txt", "r");
// display the content of the file
printf("\nFile content:\n");
while( (ch = getc(fptr)) != EOF ) {
printf("%c", ch);
}
printf("\nEnd of file\n");
// close file
fclose(fptr);
return 0;
}
In memberlist do you check if the fopen works well ? Probably fptr is NULL
Several remarks in addmember() :
addmember call itself at the end of its body, unconditionally, it is an infinite recursion
for each recursive call you fopen("username.txt", "w"); and that for nothing, but you never close the file
only one character is read for the name, it's suspicious

C - fopen text file after building - OpenWRT - opkg

I have these lines in my C program:
int main(int argc, char **argv) {
int i=0, p=0;
FILE* fp;
fp = fopen("jacina.txt", "w+");
fscanf (fp, "%d", &i);
if (ftruncate(fp, 0) == -1) {
perror("Could not truncate")
};
p = i+10;
fprintf(fp, "%d", p);
}
After building this code to OPKG in OpenWRT (from Ubuntu), how can I read and write to this textual file which is located on any disk location where is located this OPKG?
Your code doesn't make any sense. To write the input given by user to a file:
Create a file first. Take input from user (say any string) and write it to the file with the help of file descriptor (fp) and close the file so that all buffers get flushed.
FILE *fp;
char comment[100] = {0};
fp=fopen("tempfile.txt","w");
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
printf("Enter String: ");
gets(comment);
fwrite(comment, sizeof(comment), 1, fp) ;
fclose(fp);
fprintf() too can be used instead to write data into a file.
Similarly to read from a file you can use fgets() or fread() to store the contents of the file in a buffer and display the contents of the file. Hope it helps.

Storage manager function to implement read operations on a file

How to adapt my program to perform the following operations:
1.To read first block of a file
2.To read current block of a file
3.To read previous block of a file
4.To read next block of a file
5.To read last block of a file
The following is the code written by me to read a data file using a file pointer and I want to implement the above operations
void main()
{
FILE *fptr;
char filename[15];
char ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}
Any suggestions would be helpful.

Resources