Issues with fputs - c

I'm doing and small exercise where I choose a file and I want the content of the file in reverse, I got problems in the last loop, this is the error I got Process returned -1073741819 (0xC0000005) execution time : 5.427 s
Example:
File1:
Line1
Line2
Line3
File2:
Line3
Line2
Line1
This is my code
#define MAXCHAR 1000
int main()
{
FILE *fptr1, *fptr2;
char filename[MAXCHAR];
int i=0;
char *lines[4];
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s \n", filename);
exit(0);
}
for(i=0;fgets(filename, MAXCHAR, fptr1) != NULL; i++){
lines[i] = filename;
//printf("%s", lines[i]);
}
//FILE 2
printf("\n Enter the filename to open for writing \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
for(i = 4; i > 0;i--){
fputs(lines[i],fptr2);
}
fclose(fptr1);
fclose(fptr2);
return 0;
}

Related

C reading values from a binary file and then print them

I have this code, and want that the program reads/loads the data that is on the file and them printed them, but this didn´t work.
I can´t write on the file, but can´t read it.
I want that when the program initialize, he already have loaded the info that is in the the binary file, so the user can use it, for example for searching people.
#include <stdio.h>
#include <stdlib.h>
#define MAX_PERSON 3
#define FILENAME "person.bin"
typedef struct {
int id;
char fname[20],lname[20];
}person;
typedef struct {
int counter;
person persons[MAX_PERSON];
}Persons;
int writeStruct(Persons *persons,char *file){
FILE *outfile;
outfile = fopen (file, "ab+");
if (outfile == NULL){
exit(EXIT_FAILURE);
}
printf("\nInsira a informações da pessoa \n");
printf("Código: ");
scanf("%d", &persons->persons[persons->counter].id);
printf("Primeiro Nome: ");
scanf("%s", persons->persons[persons->counter].fname);
printf("Último Nome: ");
scanf("%s", persons->persons[persons->counter].lname);
fwrite (&persons, sizeof(Persons), persons->counter, outfile);
if(fwrite != 0){
puts("Sucess on writing on file");
}else{
puts("Error on writing on file");}
fclose (outfile);
return persons->counter++;
}
void loadStruct(Persons *persons,char *file){
FILE *infile;
// Open person.bin for reading
infile = fopen(file, "rb+");
if (infile == NULL) {
fprintf(stderr, "\nError opening file\n");
exit(1);
}
// read file contents till end of file
fread(&persons, sizeof (Persons), persons->counter, infile);
// close file
fclose(infile);
}
void listPersons(Persons persons){
int i;
puts("Lista de pessoas");
puts("-----------------");
for(i=0;i < persons.counter; i++) {
printPerson(persons.persons[i]);
}
puts("-----------------");
}
void searchPeople(Persons persons) {
int number;
printf("Indique o código da pessoa que pretende procurar: ");
scanf("%d",&number);
number = searchPerson(persons,number);
if (number != -1) {
printPerson(persons.persons[number]);
} else {
puts(ERROR_PERSON_NOT_EXISTS);
}
}
int searchPerson(Persons persons,int number) {
int i;
for (i = 0; i < persons.counter; i++) {
if (persons.persons[i].id == number) {
return i;
}
}
return -1;
}
void printPerson(person person){
printf("%d - %s %s\n", person.id,person.fname, person.lname);
}
int main ()
{
int op;
Persons persons ={.counter = 0};
loadStruct(&persons,FILENAME);
do{
puts("PESSOAS - BASE DE DADOS");
puts("-----------------");
puts("2 - Inserir pessoa");
puts("3 - Listar pessoas");
puts("4 - Procurar pessoa");
puts("0 - Sair");
puts("-----------------");
printf("Nº Pessoas: %d/%d \n", persons.counter, MAX_PERSON);
printf("Opção:");
scanf("%d",&op);
printf("\n");
switch (op) {
case 0:
exit(0);
break;
case 2:
writeStruct(&persons,FILENAME);
break;
case 3:
listPersons(persons);
break;
case 4:
searchPeople(persons);
break;
default:
puts("Opção inválida!");
break;
}
}while(op!=0);
}
You're just writing one Persons structure to the file. You shouldn't use persons->counter as the number of items that you're writing or reading, as the array is entirely contained in the structure.
You also shouldn't open the file in append mode. Since you're writing the entire Persons structure, not a single person, you should open it in write mode and overwrite the whole file.
The first argument to fwrite() and fread() should be persons, not &persons, since you want to fill in the structure that it points to, not overwrite the pointer.
To make sure you don't write outside the array, you should check that persons->counter hasn't exceeded the size of the array.
int writeStruct(Persons *persons,char *file){
FILE *outfile;
if (persons->counter >= MAX_PERSON) {
puts("File is full\n");
return persons->counter;
}
outfile = fopen (file, "wb");
if (outfile == NULL){
exit(EXIT_FAILURE);
}
printf("\nInsira a informações da pessoa \n");
printf("Código: ");
scanf("%d", &persons->persons[persons->counter].id);
printf("Primeiro Nome: ");
scanf("%s", persons->persons[persons->counter].fname);
printf("Último Nome: ");
scanf("%s", persons->persons[persons->counter].lname);
fwrite (persons, sizeof(Persons), 1, outfile);
if(fwrite == 1){
puts("Success on writing on file\n");
}else{
puts("Error on writing on file\n");
}
fclose (outfile);
return persons->counter++;
}
void loadStruct(Persons *persons,char *file){
FILE *infile;
// Open person.bin for reading
infile = fopen(file, "rb");
if (infile == NULL) {
fprintf(stderr, "\nError opening file\n");
exit(1);
}
// read file contents till end of file
fread(persons, sizeof (Persons), 1, infile);
// close file
fclose(infile);
}

How to store string to txt file

void inserting()
{
char file_name[50];
char sentence[1000];
FILE *fptr;
printf("File name (With extn):");
scanf("%s", file_name);
fptr = fopen(file_name, "a");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%s", sentence);
fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
I want to store content from string to file... but it is displaying everything except the first word..
INPUT : Hello this is C program //which I have entered
OUTPUT: this is C program //this is what stored in file
#include<stdio.h>
void inserting()
{
char file_name[50]="C:\\Users\\Dev Parzival\\Desktop\\foo.txt";
char sentence[1000];
FILE *fptr;
//printf("File name (With extn):");
//scanf("%s", file_name);
fptr = fopen(file_name, "w");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%[^\n]", sentence);
printf(sentence);
//fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
int main(){
inserting();
}
scan will not read spaces with%s u have to include spaces also I assume thats why use %[^\n]format specifier.
If you want to preserve your code make the adjustment
void inserting(){
char file_name[50];
char sentence[1000];
FILE *fptr;
printf("File name (With extn):");
scanf("%s", file_name);
fptr = fopen(file_name, "a");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%s", sentence);
fprintf(fptr,"%s",sentence); //<-- HERE
fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
Or you can use something like getline just to be cleaner.

trying to save data that is in an array to a file

This is my attempt at saving to a file. Once I enter the filename, it will save a file with that name, but it does not print anything to it and I dont get why.
if (menuoption == 6)
{
printf("please enter a file name\n");
scanf("%s", filename);
filepointer = fopen(filename, "a");
if (filepointer == NULL);
{
printf("unable to open file name: %s\n", filename);
continue;
}
fprintf(filepointer, "decimal values:");
for (int i = 0; i < doubcount; i++)
{
fprintf(filepointer, "%lf \n", doubles[i]);
}
fprintf(filepointer, "\n");
fprintf(filepointer, "integer values: ");
for (int i = 0; i < intcount; i++)
{
fprintf(filepointer, "%d\n", ints[i]);
}
fprintf(filepointer, "\n");
}
Here a sample I just wrote to show you how you should handle files in C
#include <stdio.h>
int main(void){
char* filename;
FILE* fp;
printf("Enter a file name:\n");
scanf("%s", filename);
fp = fopen(filename, "w");
if(fp == NULL){
fprintf(stderr, "unable to open file name: %s\n", filename);
return -1;
}
fprintf(fp, "Testing\n");
fclose(fp);
}
First of all, you should use "w" instead of "a" in fopen function
fp = fopen(filename, "w");
You can read about the modes you can open a file here http://man7.org/linux/man-pages/man3/fopen.3.html
Then you should always close a file after reading or writing it, so add this line to your code
fclose(fp);
I hope this can work for your, unfortunately I couldn't run your code, because it lacks of variable declarations, includes and all other stuff

Why is my file pointer always NULL, even with text in it?

I am having trouble opening and parsing a file in C. As of now I am trying to open a file and print out the current line then the next until the program reaches the end of the file. However, the file pointer always returns NULL and does not read the file.
This is my function:
int file_parse() {
char filename[100];
printf("Enter the filename: ");
scanf("%s", filename); //Get filename
printf("\nYou want to encrypt or decrypt with file: %s", filename); //Confirm filename
int origin[27];
int final[27];
FILE *fp;
if ((fp = fopen(filename, "r")) != NULL) {
char current_line[250];
while (!feof(fp)) {
fgets(current_line, 250, fp);
printf("The current line is: %s", current_line);
}
fclose(fp);
} else {
printf("\nError! Cannot open the specified file.");
exit(EXIT_FAILURE);
}
}

Write to .txt file?

How can I write a little piece of text into a .txt file?
I've been Googling for over 3-4 hours, but can't find out how to do it.
fwrite(); has so many arguments, and I don't know how to use it.
What's the easiest function to use when you only want to write a name and a few numbers to a .txt file?
char name;
int number;
FILE *f;
f = fopen("contacts.pcl", "a");
printf("\nNew contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);
fprintf(f, "%c\n[ %d ]\n\n", name, number);
fclose(f);
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, pi);
/* printing single characters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);
Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

Resources