Here I am writing some data to a file and trying to display that data.Is it compulsory to use fscanf before printing that data on the output screen? When I use the fscanf and suppose I enter the details as:
Ram
usa
12
the output comes as
Ramusa1212
What might be the possible error here?
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
FILE *fptr;
char name[20],address[20];
int roll;
fptr=fopen("1.txt","w");
if(fptr!=NULL){
printf("file created successfully:you can write into the file now");
}
else{
printf("error creating file");
exit -1;
}
printf("enter your name,address,roll number");
fgets(name,20,stdin);
scanf("%s",address);
scanf("%d",&roll);
fprintf(fptr,"%s%s%d",name,address,roll);
fclose(fptr);
fptr=fopen("1.txt","r");
fscanf(fptr,"%s%s%d",name,address,&roll);
printf("%s%s%d",name,address,roll);
fclose(fptr);
getch();
}
Related
i'm new here and i'm trying to solve a FILE problem in c. Basically i have to create a program that lets the user input how many lines he wants to write in a file, create a new file, write those lines and the reading it and establish how many lines where written and print the number of lines.
int main() {
int x, lc=0;
char str[100];
FILE *fp=fopen("test.txt","w");
if (fp==NULL) {
printf("\nOpening failed");
}else{
printf("\nOpened correctly");
}
printf("\nStrings to write:\n");
scanf("%d",&x);
for (int i = 0; i < x; i++) {
fgets(str, sizeof str, stdin);
fputs(str,fp);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL) {
lc++;
}
fclose(fr);
printf("\nThere are %d lines",lc);
return 0;
}
If i leave the code like this it messes up with my for cycle and it only lets me write 3 lines because it does put a free line at the start of the file. Can you explain how do i solve that? or if it's just how fgets and fputs behave and i have to remember that blank line at the start. Thank you in advance. (i'll leave a file output as follows with numbers for the lines)
1)
2)it seems to work
3)dhdhdh dhdh
4)random things
As you can tell from the comments, there are a lot of ways to approach this task. The usage of "scanf" and "fgets" can get complex especially if mixed within the same reading task. But, just to give you one option as to deriving a solution, following is a snippet of code to offer one of many possible routes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x, lc=0;
char str[101];
FILE *fp=fopen("test.txt","w");
if (fp==NULL)
{
printf("Opening failed\n");
}
else
{
printf("Opened correctly\n");
}
printf("Strings to write: ");
scanf("%d",&x);
for (int i = 0; i < x; i++)
{
printf("Enter string: ");
scanf("%s", str);
fprintf(fp, "%s\n", str);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL)
{
lc++;
}
fclose(fr);
printf("\nThere are %d lines\n",lc);
return 0;
}
You will note that both "scanf" and "fgets" are being used in this example, but not in reference to the same file. For user input, "scanf" is getting used. Once the file is closed and then reopened for reading, "fgets" is being used for that portion of the task.
Testing this program snippet out resulted in matching up the same quantity of lines read from the file as were entered.
#Una:~/C_Programs/Console/FileWrite/bin/Release$ ./FileWrite
Opened correctly
Strings to write: 4
Enter string: Welcome
Enter string: to
Enter string: Stack
Enter string: Overflow
There are 4 lines
Give it a try and see if it meets the spirit of your project.
This may have some other mistakes. But the only thing I concern is fscanf. It doesn't read new line. It reads only the first line. Can you please tell me how to fix it.
#include <stdio.h>
#include<stdlib.h>
int main(void){
int no = 0;
FILE *cPtr;
cPtr = fopen("number.dat","a");
if(cPtr==NULL){
printf("Unexpected error detected while creating new file\n");
}
do{
printf("Enter your number : ");
scanf("%d",&no);
if(!(no==-99)){
fprintf(cPtr,"%d\n",no);
}
}while(!(no==-99));
fclose(cPtr);
int n,i;
FILE *fp;
fp=fopen("number.dat","r");
if(fp==NULL){
printf("Error");
exit(1);
}
for(i=1;i<10;i++){
fscanf(fp,"%d",&n);
printf("\n%d",n);
fclose(fp);
}
}
I wrote the following code but when i enter "abcd" it shows "dcb" and skips the first character.I know that my logic in the while loop crosses the file boundary but fseek(f2) is still not 0 when it crosses the file boundary.It should return some negative value.
#include<stdio.h>
int main()
{
FILE *f1,*f2;
char ch;
clrscr();
f1=fopen("Input","w");
while((ch=getchar())!=EOF)
putc(ch,f1);
fclose(f1);
f2=fopen("Input","r");
fseek(f2,-1L,2);
while(ftell(f2)!=0)
{
ch=getc(f2);
printf("%c",ch);
fseek(f2,-2L,1);
}
fclose(f2);
getch();
return(0);
}
You need a do-while loop, not a while-do loop.
You need to read the character when ftell() returns zero, but NOT read anymore. That's usually the indication you need a bottom-tested loop and not a top tested one.
#include <stdio.h>
int main(){
FILE *fp;
int ch;
fp=fopen("out.txt","w");
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen("out.txt","rb");
fseek(fp,0L,SEEK_END);
while(fseek(fp,-2L,SEEK_CUR)==0){
ch=fgetc(fp);
putchar(ch);
}
fclose(fp);
return(0);
}
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 havent been successful
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
{
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
int i;
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;
}
There are several problems.
You are trying to read from fileptr.
You are reading only one character, but treat the name array as if it was read in correctly.
A start would be:
[...]
printf("Enter name: \n");
if (fgets(name, sizeof name, stdin)) {
fputs(name,fileptr);
fclose(fileptr);
printf("File write was successful\n");
} else {
printf("Read error.\n");
}
But that's not all: you have forgotten to put error checking. E.g., how do you know that your "File write was successful\n" if you don't check at least the return value of fputs()?
I'm creating a program that asks the user to input a word. The word is then compared with a word in a text file. If correct, I want the user to input another word which should correspond with the next word in the text file and this should loop until the end of the file. I'm having trouble with the loop to the end of the file. Could someone please review my code and give me a few pointers? thanks so much
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}
i made some suggestions about scanf_s and fscanf_s, if they are available, use them. But still, i am wondering why they are still teaching bad code in schools? I would not suggest to use *scanf* functions at all. Further reading: uncontrolled format string
Move the fscanf call that reads from the file to a function that returns the next word
loop for user input, only calling the function outlined above when you need to advance to the next word in the file (when the user inputs the correct thing)