Read mpq_t from a binary file - c

I have written mpq_t to a binary file called "data", and now I am trying to read mpq_t from the file one by one, but I kept having segfault at the line: gmp_printf("%Qd\n", buf). I've been debugging for a while but couldn't figure out where went wrong.
int main(){
FILE *fp = fopen("data", "rb");
if (fp == NULL){
perror("FILE open failed");
exit(1);
}
mpq_t buf;
mpq_init(buf);
while (fread(&buf, sizeof(mpq_t), 1, fp) == 1){
gmp_printf("%Qd\n", buf);
}
fclose(fp);
return 0;
}
It seems that I have a memory issue with buf after reading from the file. I have also tried mallocing instead of initiating, but it did not work either.
mpq_t *buf = (mpq_t *)malloc(sizeof(mpq_t));
if (buf == NULL){
perror("malloc failed");
exit(1);
}
while (fread(buf, sizeof(mpq_t), 1, fp) == 1){
gmp_printf("%Qd\n", *buf);
}

Use gmp_fprintf and gmp_fscanf to write and read:
gmp_fprintf (FILE *fp, const char *fmt, ...)
gmp_fscanf (FILE *fp, const char *fmt, ...)

Related

Unable to read from file from argv

I am trying to read from a file, and here is my code, but as I run my code nothing shows up. Have I used the getline() function incorrectly? I can not understand my problem.
const char *READ = "r";
/**
* main - Entry point of my program
*
* Return: On success, it returns 0. On
* error it returns -1
*/
int main(int ac, char **av)
{
FILE *fpointer;
char *lineptr = NULL;
size_t *n = 0;
int line_number = 1;
if (ac != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
fpointer = fopen(av[1], READ);
if (fpointer == NULL)
{
fprintf(stderr, "Error: Can't open file %s\n", av[1]);
exit(EXIT_FAILURE);
}
while (getline(&lineptr, n, fpointer) != -1)
{
printf("Line %d: %s\n", line_number, lineptr);
line_number++;
}
return (0);
}
getline(&lineptr, n, fpointer) returns -1. You did not explicitly check this and print an error message.
Checking errno it's because of EINVAL: invalid argument. Also good to check errno.
Reason is that n is NULL, while a pointer to an existing size_t is required.
BTW, indenting with 8 spaces is rather uncommon; I'd stay with 4 space. (Also, never use TAB characters.)
It's advisable to stick with extremely common argc and argv.
Nice you put {s on a further empty line; I like that style.
You'd get this:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
const char *READ = "r";
int main(int argc, char **argv)
{
FILE *fpointer;
char *lineptr = NULL;
size_t n;
int line_number = 1;
if (argc != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
fpointer = fopen(argv[1], READ);
if (fpointer == NULL)
{
fprintf(stderr, "Error: Can't open file '%s'.\n", argv[1]);
exit(EXIT_FAILURE);
}
if (getline(&lineptr, &n, fpointer) == -1)
{
printf("Failed to read file '%s': %s.\n", argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
do
{
printf("Line %4d: %s\n", line_number, lineptr);
line_number++;
}
while (getline(&lineptr, &n, fpointer) != -1);
return (0);
}
Declaration of getline:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
As an output parameter, the type of n is size_t *. It points to a space for writing by getline.
But in your code, n points to 0, which is NOT a vaild addr to write in.

c - print file in hexa after fread

I have this code that read binary file content and then write it but fwrite print it as chars and I need to print the hexa value of each byte. I only find a way to do it using fprint (using format '%x')
void PrintHex(int *buffer, int length){
fwrite(buffer,length, 1 ,stdout);
}
int main(int argc, char **argv) {
FILE *inptr = fopen ( argv[1], "rb");
if (inptr == NULL)
{
fprintf (stderr, "Could notopen %s", argv[1]);
return 1;
}
int buffer[1000];
while (fread (&buffer, 1, 1, inptr) == 1)
{
PrintHex(buffer, 1);
}
fclose(inptr);
return 0;
}

How does FILE stream buffer work?

I understand fopen() opens file and creates a buffer for read and write operations on that file. fopen() returns a pointer for that buffer.
So my question is, in the code below, the _copy function body has a temp matrix to transfer between the fread() and fwrite(). why cant I directly transfer from buffer to buffer?
/* example: copyfile.exe xxxxx.txt zzzzzz.txt */
#include <stdio.h>
#include <stdlib.h>
#define BUFF 8192
void _copy(FILE *source, FILE *destination);
int main(int argc, char *argv[])
{
FILE *fp1, *fp2; // fp1 source file pointer// fp2 copied file pointer
if (argc !=3 ) //command line must have 3 arguments
{
fprintf(stderr, "Usage: %s (source file) (copy file)\n", argv[0][0]);
exit(EXIT_FAILURE);
}
if ((fp1 = fopen(argv[1], "rb")) == NULL) //Opening source file
{
fprintf(stderr, "Could not open %s\n",argv[1]);
exit(EXIT_FAILURE);
}
if((fp2 = fopen(argv[2], "ab+")) == NULL) //Opening destination file
{
fprintf(stderr, "could not create %s \n",argv[2]);
exit(EXIT_FAILURE);
}
if( setvbuf(fp1,NULL, _IOFBF, BUFF) != 0) //Setting buffer for source file
{
fputs("Can't create output buffer\n", stderr);
exit(EXIT_FAILURE);
}
if( setvbuf(fp2,NULL, _IOFBF, BUFF) != 0) //Setting buffer for destination file
{
fputs("Can't create input buffer\n", stderr);
exit(EXIT_FAILURE);
}
_copy(fp1, fp2);
if (ferror(fp1)!=0)
fprintf(stderr, "Error reading file %s\n", argv[1]);
if(ferror(fp2)!=0)
fprintf(stderr, "Error writing file %s\n",argv[2]);
printf("Done coping %s (source) to %s (destination) \n",argv[1], argv[2]);
fclose(fp1);
fclose(fp2);
return (0);
}
void _copy(FILE *source, FILE *destination)
{
size_t bytes;
static char temp[BUFF];
while((bytes = fread(temp,sizeof(char),BUFF,source))>0)
fwrite(temp,sizeof(char),bytes,destination);
}
You cannot use the underlying buffer from a FILE * in another FILE *. As you were told in comment, FILE * is an opaque pointer. But you can avoid the overhead of copying data between buffers by forcing both files in non buffered mode:
setbuf(fp, NULL); // cause the stream to be unbuffered

how to copy result of the linux command into a string using c code?

I have executed a command "watch grep \"cpu MHz \" /proc/cpuinfo".After executing this command i got following result.
Result of The Command
But when I am trying this command using c code.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char path[1035];
char command[]="watch grep \"cpu MHz \" /proc/cpuinfo";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}
I am getting following result.
Result of The Code
tell me where am I going wrong?
Try something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp;
char path[1035];
char command[]="while grep \"cpu MHz\" /proc/cpuinfo; do sleep 2; done";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}
I think this is what you want.
Don't forget to use memset.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char path[1035];
char command[]="watch grep 'cpu MHz' /proc/cpuinfo";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
memset(path,'\0',sizeof(path));
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}

C: fgets always NULL

I'm playing with file I/O in C.. I'm trying to use fgets to read data in from one file and output it to another file. The problem is that it always returns NULL and so nothing gets copied to the output file. Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpIn;
FILE *fpOut;
if ((fpIn = fopen("C:\\testIn.txt", "r") == NULL))
{
printf("Cannot open input file!\n");
exit(1);
}
if ((fpOut = fopen("C:\\testOut.txt", "a") == NULL))
{
printf("Cannot open output file!\n");
exit(1);
}
char buffer[128];
while (fgets(buffer, 128, fpIn) != NULL)
{
fputs(buffer, fpOut);
}
fclose(fpIn);
fclose(fpOut);
system("PAUSE");
return 0;
}
another thing; when I tried using "a+f" in the second arg for fopen, it didn't work.
if ((fpOut = fopen("C:\\testOut.txt", "a") == NULL))
Should be
if ((fpOut = fopen("C:\\testOut.txt", "a")) == NULL)
Same on the input file.
If you are new to C, I'd suggest do one thing at a time to make it easier to track down issues.
e.g.
fpOut = fopen("C:\\testOut.txt", "a");
if(fpOut == NULL) {
...

Resources