Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a file y.txt that contains the text abcdefgh
this code convert file descriptor(int fd) to file pointer (FILE*), and tries to read from it.
#include <stdio.h>
#include<fcntl.h>
int main()
{
FILE *fp;
int fd = open("y.txt",O_RDONLY);
printf("%d",fd);
fp=fdopen(fd,"r");
close(fd);
char a[5];
a[4]='\0';
fread(a,2,1,fp);
printf("%s",a);
return 0;
}
The program outputs p instead of ab, as it should if it is reading from the begining of y.txt.
What am I doing wrong?
I see a problem with your code. You close(fd) before you are done with fp, which is probably causing your calls to fread to fail. This is because when you use fdopen:
The file descriptor is not dup'ed.
meaning that the underlying file that fp is trying to read from gets closed when you run close(fd). To fix this, you can remove the call to close and add a call to fclose which should close fd as well.
if you really just want a FILE * you should just be able to use fopen to open it, skipping the fd all together.
Consider your code:
char a[5];
a[4]='\0';
fread(a,2,1,fp);
This gives you a 5 character string. It is an "auto" variable and is not initialized. Then you terminate the string with a '\0'. Good. Then you fread one item of size 2. So bytes 3 and 4 are still garbage. Does this help?
Here are a few corrections to the program, as commented in the code.
#include <stdio.h>
#include <io.h> // added header
#include <fcntl.h>
int main()
{
FILE *fp;
int fd = open("y.txt",O_RDONLY);
printf("%d\n",fd); // add a newline for clarity
fp=fdopen(fd,"r");
//close(fd); // do not close before reading!
char a[5];
a[4]='\0';
fread(a,4,1,fp); // read 4 chars to fill the string space
printf("%s\n",a); // add a newline for clarity
close(fd); // close after reading
return 0;
}
File input:
abcde
Program output:
3
abcd
Although it would be better in the first place to have the simpler
FILE *fp = fopen("y.txt", "r");
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I need help with this code. You see, it is taking inputs likes strings and integers and saves them in two arrays . Those two should be written into a file with the name "Lagerverwaltung.text". However it just prints a 0 and nothing else into the file.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char artnr[50],menge[50],me[50],neu[50],date[50];
int zahl, calcam, id, sub,amount;
int greatlen = 0;
int result = 0;
char str[50][50][50];
int mengen[10];
int a = 1;
int s = 0;
while(a > 0){
FILE* fp;
fp = fopen("Lagerverwaltung.txt", "w");
printf("Geben sie eine Zahl ein:");
scanf("%d", &zahl);
if(zahl == 1){
printf("Geben sie ein:\nArtikelnr.:");
scanf("%s",&artnr);
strcpy(str[s][0],artnr);
printf("Menge:");
scanf("%d",&mengen[greatlen]);
printf("Mengeneinheit:");
scanf("%s",&me);
strcpy(str[s][1],me);
printf("Datum:");
scanf("%s",&date);
strcpy(str[s][2],date);
}
fputs(str[greatlen][0], fp);
fprintf(fp, "%d", mengen[greatlen]);
fputs(str[greatlen][1], fp);
fputs(str[greatlen][2],fp);
fclose(fp);
s =s+1;
greatlen = greatlen +1;
}
return 0;
}
There should be a line of integers and strings written into a file.
fopen with "w" parameter opens the file and discards existing content. That means that in each loop iteration you discard whatever you have written previously. Since a never goes to 0, the only option to end the program is to abort it, and you'll be doing that while it waits for input, which is after it has already discarded any file content but before it has written new content.
Possible fixes:
open the file with "a" to append to it
open the file before the loop and close it after the loop (while providing a way to exit the loop).
Also, fix the string-scanning lines like
scanf("%s",&artnr);
that should be
scanf("%s", artnr);
and every decent compiler would warn you about it.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to read file with C program here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fptr;
fptr = fopen("text.txt","r");
char arr[150];
char c;
int i;
while(!feof(fptr) && i<5)
{
printf("%d\n",i++);
fgets(arr,150,fptr);
puts(arr);
}
fclose(fptr);
return 0;
}
When executed the program wont stop and the characters printed are weird, i dont know what is going wrong ?
The part causing error in your program is :
while(!feof(fptr))
Better read : What is wrong with "while(!feof(fptr))" and Why it's bad to use feof() to control a loop
A simple program to read is below which checks if file is opened or not. It's a good practice to check if file you are to perform operations on is opened or not.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("text.txt", "r"); // read mode
if (fp == NULL) //Checking if file is open
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF){
printf("%c", ch); //Avoided creating a buffer
}
fclose(fp);
return 0;
}
#Though not so much realevant!!
I think the easiest way to read/write from/to file is using freopen() function. You can use scanf() & printf() in case of C and cin & cout in case C++ to read or write from file with this function.
Read from file: freopen("input.txt","r",stdin); where input.txt is filename.
Write to file: freopen("output.txt","w",stdout); no need to create output.txt your own. The file is automatically created when the program is executed.
This question already has an answer here:
Garbage Value in File after write
(1 answer)
Closed 5 years ago.
i am trying to copy to a file the contents of two input files in c with the help of read, write and open. At first i tried to simply copy the contents of only one file that contains the 'hello' world, but this is what gets written:
"hello
h«Ú^?^#^#^A^#^#^#^#^#^#^#m G«Ú^?^#^#^#^#^#^#^#^#^#^#^Pjh«Ú^?^#^#^A^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^A^#^#^#þ^?^#^#°<91>h«Ú^?^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^#^H<95>h«Ú^?^#^#P)»Ó
"
my code is:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc , char *argv[]){
int fd1,fd2,fdout;
int fread1, fread2;
char buff[128];
int fconf(int f1, int f3){
fd1 = open(argv[1],O_RDONLY);
fdout = open(argv[2],O_RDONLY | O_CREAT | O_APPEND | O_RDWR);
fread1 = read(fd1,buff,sizeof(buff));
write(fdout,buff,sizeof(buff));
close(fd1);
close(fdout);
return 0;
}
}
I have no idea why this happens.
Probably your input file contains less than 128 bytes. But you always attempt to write all 128 bytes from your buffer to your output file. Bytes after what was read are uninitialized garbage.
Use the return value of read to know how many bytes you actually got.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I was asked to solve a programming challenge, and there is this line which I don't understand can some one explain to me how can I pass the test cases to the program using this command, I think I have to store it in some file but I am not sure
size_t getline(char **lineptr,size_t *n, FILE *stream);
here is the full code
#include <stdio.h>
#include <stdlib.h>
size_t getline(char **lineptr,size_t *n, FILE *stream);
int main()
{
size_t maxLineLen=1024;
char *line = (char*)malloc(maxLineLen);
while(getline(&line, &maxLineLen,stdin)!= -1){
printf("Hello, World!\n");
printf("%s\n",line);
}
}
Seems you are asking how to run the given code and get input into.
getline(&line, &maxLineLen,stdin)
That reads a line from stdin. stdin is a standard file stream and is opened by the startup code for you. Without redirection, reading from stdin will get the input typed into the terminal
So to get input into the program you can do one of the following:
Run the program and then type each input line into the terminal.
Run the program and then redirect a file into the program. Example:
./my_program < my_input.txt
Are you given a file name?
Then the FILE * parameter would have to be opened via fopen.
See manual for fopen
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have this bit of C code below. When I place printf statements to test the text from the input file, I see that I'm getting a bunch of junk values, to be more specific they are not even alphabetic or numerical, I think they are diamonds with question marks in them. I assume this means it is not processing these values the way it should be. The input file a bit of MIPS assembly code, but in this context it is only a text file. I have commented out all other parts of my program and am left with this small piece and yet I still receive the bad values. What could I possibly be doing wrong here?
The command I use to run the program on the console is:
./assembler -symbols adder.asm
Where ./assembler is the driver (argv[0])
-symbols is a tag used (argv[1])
adder.asm is the input file (argv[2])
So once opened I should be able to grab text out of this file, and it's not a problem with the file as far as I believe, it was working earlier.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
FILE *fp;
FILE *fp_out;
void main(int argc, char* argv[])
{
int mode;
if (strcmp(argv[1], "-symbols") == 0)
{
fp = fopen(argv[2], "r");
mode = 1;
}
else
{
fp = fopen(argv[1], "r");
fp_out = fopen(argv[2], "w");
mode = 2;
}
}
Try to add the following line right after the open section and add #include <errno.h> to the beginning.
printf("%p, %p, %d\n", fp, ftp_out, errno);
If the fp is null then there is some problem opening the file. If you do not check the return value, you can read from a wrong buffer. Maybe there is some permission problems (or whatever). Also if errno != 0 you have a problem. Check with perror <num> the errno value in command line (or see perror(3) function).