I want to read strings and write them as full lines into a file, but I can't read more words into a buffer as a complete string.
Current problematic code:
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
tab = (char**)malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
printf("\nEnter sentence: ");
scanf("%s", val);
tab[i] = _strdup(val);
}
for (i = 0; i < n; i++)
fprintf(f, "%s ", tab[i]);
free(tab);
Previously I tried this: (problem is this only assigns one string)
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter sentence: ");
scanf("%s", val);
fprintf(f, "\%s ", val);
}
Almost there, now i have sentences but i got one empty line as first line of file.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string>
#define SIZE 30
void creare(char t[30]);
void main(void)
{
FILE* f2;
char name[30];
printf("\nEnter name of file to work with: ");
scanf("%s", name);
creare(name);
f2 = fopen(name, "r");
if (f2 == NULL)
{
printf("\nOpen error!!");
exit(0);
}
fclose(f2);
printf("\n");
_getch();
}
void creare(char t[30])
{
FILE* f;
int n,i;
char val[30];
f = fopen(t, "w");
if (f == NULL)
{
printf("\nOpen error!!");
exit(0);
}
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
for (i = 0; i <= n; i++)
{
fgets(val, sizeof(val), stdin);
fprintf(f, "% s", val);
}
fclose(f);
}
I have used fgets(val, sizeof val, stdin) to read the string, because to read string with spaces.
The reason why that blank line comes in file is due to the fact that you are reading "\n" that is inputted after scanf("%d", &n);The keystroke "\n" will be read into val for the first time so it simply prints that "\n" to the file.
In order to read that "\n" use a character to read that "\n". Below is the complete program.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define SIZE 30
void creare(char t[30]);
int main(void)
{
FILE* f2;
char name[30];
printf("\nEnter name of file to work with: ");
scanf("%s", name);
creare(name);
f2 = fopen(name, "r");
if (f2 == NULL)
{
printf("\nOpen error!!");
exit(0);
}
fclose(f2);
printf("\n");
}
void creare(char t[30])
{
FILE* f;
int n,i;
char val[30],g;
f = fopen(t, "w");
if (f == NULL)
{
printf("\nOpen error!!");
exit(0);
}
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
scanf("%c",&g);
for (i = 0; i <n; i++)
{
fgets(val, sizeof(val), stdin);
fprintf(f, "%s", val);
}
fclose(f);
}
Related
I have written a small program to read in a series of strings from a file and then to store them in a 2D Arrray. The strings are read into the array correctly, yet my program is not countering the number of rows in the file like I had expected.
I am honestly at a loss and cannot figure out why the program is not counting the rows in the file. Any explanation as to what I am doing wrong is greatly appreciated.
Here is the code that I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp;
char nameArray[20][120], str[20];
int i = 0, j = 0, n;
int count = 0;
char name[20]; //filename
int ch;
printf("Please enter a file name: ");
scanf("%s", &name);
fp = fopen(name, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!\n", name);
return -1;
}
while (fscanf(fp, "%s", str) != EOF)
{
strcpy(nameArray[i], str);
i++;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
count++;
}
for (i = 0; i<=count; i++)
{
printf("%s", nameArray[i]);
}
fclose(fp);
return 0;
}
I need to solve a problem. I need to create two functions which scan user's input information and put in into structure array and then put all array to BIN file (with function fwrite()) and other function - read from BIN file with function fread(). You can see my code below. Problem is that I can write to file, but when I read I get filler array element and other element which are empty. How to get only filled struct array element?
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
typedef struct
{
char Lesson[50];
char TeachersName[50];
char TeachersLastName[50];
int Credits;
int NumberOfStudents;
} School;
void ToFile (char *fileName);
void FromFile (char *FileName);
int main()
{
char *fileName[]={"student.bin"};
ToFile (*fileName);
FromFile (*fileName);
return 0;
}
void ToFile (char *fileName)
{
int n, chars;
FILE *fp;
fp = fopen(fileName, "wb");
School Info[20];
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fwrite() function: \n\n");
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(int i = 0;i<n;i++)
{
printf("\nEnter details of employee %d \n", i + 1);
fflush(stdin);
printf("Lesson: ");
gets(Info[i].Lesson);
printf("Teachers name: ");
gets(Info[i].TeachersName);
printf("Teachers last name: ");
gets(Info[i].TeachersLastName);
printf("Credits: ");
scanf("%d", &Info[i].Credits);
printf("Number of studens: ");
scanf("%d", &Info[i].NumberOfStudents);
chars = fwrite(&Info[i], sizeof(Info), 1, fp);
printf("Number of items written to the file: %d\n", chars);
}
fclose(fp);
}
void FromFile (char *FileName)
{
School Info[20]= { { "", "","",0,0 } };;
FILE * fpp;
fpp = fopen(FileName, "rb");
fread(&Info, sizeof(Info), 1, fpp);
/*
for(int j=0; j<20; ++j) {
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
}*/
int j=0;
while (fread(&Info, sizeof(Info), 1, fpp))
{
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
j++;
}
fclose(fpp);
}
This question already has answers here:
Removing trailing newline character from fgets() input
(14 answers)
Closed 2 years ago.
The code is working fine but whenever I type the words second time and it comes to seeing the result in a file, it gives me the result like this. How to handle this?
Name, DOB, ID, Phone
Name
, DOB, ID, Phone
The Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50
int main(){
FILE * fw = fopen("new.csv", "a");
char* listing[] = {"Name", "Date of birth","ID card number","Phone number"};
char data[4][LEN], name[LEN], amount[LEN], dob[LEN], id[LEN], option;
int i, done=0;
do{
for (i = 0; i < 4; i++) {
printf("Enter your %s: ", listing[i]);
fgets(data[i], LEN, stdin);
if(strcmp(data[i], "\n") == 0){
fgets(data[i], LEN, stdin);
}
else{
data[i][strlen(data[i])-1] = '\0';
}
}
fprintf(fw, "%s, %s, %s, %s\n", data[0], data[1], data[2], data[3]);
printf("Do you want to continue [y/n]: ");
scanf("%s", &option);
}
while(option == 'y');
fclose(fw);
return 0;
}
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50
int main() {
FILE * fw = fopen("new.csv", "a");
char * listing[] = {
"Name",
"Date of birth",
"ID card number",
"Phone number"
};
char data[4][LEN], name[LEN], amount[LEN], dob[LEN], id[LEN], option;
int i, done = 0;
do {
for (i = 0; i < 4; i++) {
printf("Enter your %s: ", listing[i]);
fgets(data[i], LEN, stdin);
while (strcmp(data[i], "\n") == 0) { //<------Changed if condition to while loop
fgets(data[i], LEN, stdin);
}
data[i][strlen(data[i]) - 1] = '\0';
}
fprintf(fw, "%s, %s, %s, %s\n", data[0], data[1], data[2], data[3]);
printf("Do you want to continue [y/n]: ");
scanf("%s", & option);
}
while (option == 'y');
fclose(fw);
return 0;
}
I changed the if statement to while loop where you checked if input is '\n'.
I made program that helps with learning english. You have code below, but for my question you don't need to read and understand what's inside. What I want to do is to create .cfg or .ini file, that can be open with simple notepad and lets user modify:
MAX size (default is 15)
Sleep(x) value (default is 500)
I have no idea how can I make such config file that can be modified by user,link it with my c code, and then after runing program.exe it accepts changes from there. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <Windows.h>
#define MAX 15 //word max size
struct slowa
{
char pl_word[MAX];
char eng_word[MAX];
};
void menu(void);
int count_lines(FILE*);
void print_array1 (const int[],int); //print 1-dimension array
void swap (int*,int*);
int main ()
{
srand( time( NULL ) );
int i,k,j;
FILE* fp;
fp = fopen ("tekst", "r");
if (!fp)
{
printf ("zjebales"); //"you fucked up"
return -1;
}
const int lines = count_lines(fp);
int tab[lines]= {};
int* temp = (int*)malloc(lines*sizeof(int));
for (j=0; j<lines; j++)
{
temp[j]=j+1;
}
j=lines;
for (i=0; i<lines; i++)
{
k=rand()%j--;
tab[i]=temp[k]-1;
swap(temp+k,temp+j);
}
free(temp);
struct slowa arr[lines];
rewind (fp);
for (i=0; i<lines; i++)
{
fscanf(fp, "%s %s", arr[tab[i]].pl_word, arr[tab[i]].eng_word);
}
fclose(fp);
char text[MAX];
k=0;
system("cls");
menu();
scanf("%d",&j);
system("cls");
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
switch (j)
{
case 1:
for (i=0; i<lines; i++)
{
printf ("Podaj tlumaczenie:%s\n", arr[i].eng_word); //"Write translation"
//fgets (text, MAX, stdin);
scanf ("%s",text);
if (strcmp(arr[i].pl_word, text) == 0)
{
puts ("DOBRZE!"); //"Correct!"
k++;
}
else puts ("ZLE!"); //"Wrong"
Sleep(500);
system("cls");
}
break;
case 2:
for (i=0; i<lines; i++)
{
printf ("Podaj tlumaczenie:%s\n", arr[i].pl_word); //"Write translation"
scanf ("%s",text);
if (strcmp(arr[i].eng_word, text) == 0)
{
puts ("DOBRZE!"); //Correct!
k++;
}
else puts ("ZLE!"); //Wrong!
Sleep(500);
system("cls");
}
break;
default:
puts ("miales podac 1 lub 2 dzbanie"); //"You should put 1 or 2"
getchar();
return -1;
}
printf ("Odpowiedziales dobrze na %d/%d pytan. ", k, lines); //"You answered correctly k/lines words"
if (k==lines) puts("No dobra cos tam umiesz");
else if(k>(lines/2)&&k<lines) puts ("Mogloby byc lepiej");
else puts ("Wracaj do nauki debilu");
while ((ch = getchar()) != '\n' && ch != EOF);
getchar();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 //just a random value
typedef struct Song
{
char *name;
char *nameSong;
char *timeSong;
int date;
} Song;
void saveToFile(Song *x, int *songCount) //Saves info to the binary file
{
FILE *f = fopen("array.txt", "w");
if (f == NULL)
{
printf("Error\n");
}
fwrite(songCount, sizeof(int), 1, f);
fwrite(x, sizeof(struct Song), (*songCount), f);
fclose(f);
}
void readSong(Song *x, int *songCount) //Reads info fromt he file and writes it
{
FILE *fr = fopen("array.txt", "r");
if (fr == NULL)
{
printf("Error\n");
}
printf("Songs:\n");
fread(songCount, sizeof(int), 1, fr);
fread(x, sizeof(struct Song), (*songCount), fr);
for(int i=0; i < (*songCount); i++)
{
printf("%d. %s %s %s %d\n", (i+1), x[i].name, x[i].nameSong, x[i].timeSong, x[i].date);
}
fclose(fr);
}
void insertSong(Song *x, int Count) //Inserts new song into the array.
{
printf("\nInsert name of the band:\n");
x[Count].name=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].name);
printf("Insert name of the song:\n");
x[Count].nameSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].nameSong);
printf("Insert length of the song:\n");
x[Count].timeSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
main()
{
int songCount, menuOption;
Song *x=malloc(SLENG*sizeof(char)+SLENG*sizeof(char)+SLENG*sizeof(char)+sizeof(int));
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch(menuOption)
{
case(1) :
printf("Insert how many songs do you want to input?\n");
scanf("%d", &songCount);
for(int i=0; i<songCount; i++)
{
insertSong(x, i);
}
saveToFile(x, &songCount);
break;
case(2) :
readSong(x, &songCount);
break;
}
}
I have an assingment to write a programm which would input some data into file and could read that data from that file, the problem is probably with fwrite or fread, couse it seems to crash everytime I try to load the and write the data from file. Any ideas why is it not working properly? And can I even do it like this as it is dynamic struct array. Thanks in advance.
In order to save the structure to a file, it must only contain scalar values, not pointers into memory objects. Modify your structure to use arrays instead of pointers:
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
And modify the code accordingly, but note that:
saving and reading the structures to and from a file requires opening it in binary mode "wb" and "rb".
it is very misleading to name a binary file array.txt.
you do not need to pass the address of the count when writing to the file, but you need to pass the address of the array pointer when reading as you do not know yet how much memory to allocate.
Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 // this value is used in the file format
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
int saveToFile(Song *x, int songCount) { //Saves info to the binary file
FILE *f = fopen("array.bin", "wb");
if (f == NULL) {
printf("Error\n");
return -1;
}
fwrite(songCount, sizeof(int), 1, f);
int written = fwrite(x, sizeof(struct Song), songCount, f);
fclose(f);
return written;
}
int readSong(Song **x, int *songCount) { //Reads info from the file and writes it
int count = 0;
FILE *fr = fopen("array.bin", "rb");
if (fr == NULL) {
printf("Error\n");
return -1;
}
printf("Songs:\n");
fread(&count, sizeof(int), 1, fr);
*x = calloc(count, sizeof(Song));
if (*x == NULL) {
printf("Cannot allocate %d bytes of memory\n", count);
fclose(fr);
return -1;
}
int found = fread(*x, sizeof(struct Song), count, fr);
for (int i = 0; i < found; i++) {
printf("%d. %s %s %s %d\n", i + 1,
(*x)[i].name, (*x)[i].nameSong, (*x)[i].timeSong, (*x)[i].date);
}
fclose(fr);
return *songCount = found;
}
void insertSong(Song *x, int Count) { //Inserts new song into the array.
printf("\nInsert name of the band:\n");
scanf("%49s", x[Count].name);
printf("Insert name of the song:\n");
scanf("%49s", x[Count].nameSong);
printf("Insert length of the song:\n");
scanf("%49s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
int main(void) {
int songCount, menuOption;
Song *x = NULL;
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch (menuOption) {
case 1:
printf("Insert how many songs do you want to input?\n");
if (scanf("%d", &songCount) == 1) {
x = calloc(songCount, sizeof(Song));
for (int i = 0; i < songCount; i++) {
insertSong(x, i);
}
saveToFile(x, songCount);
}
break;
case 2:
readSong(&x, &songCount);
break;
}
free(x);
x = NULL;
return 0;
}