Is fprintf not like printf when writing to file? - c++

I've reviewed the documentation:
It says here:
Once a file has been successfully opened, you can read from it using fscanf() or write to it using fprintf(). These functions work just
like scanf() and printf(), except they require an extra first
parameter, a FILE * for the file to be read/written.
So, I wrote my code as such, and I made sure to include a conditional statement to make sure that the file opened:
# include<stdio.h>
# include<stdlib.h>
void from_user(int*b){
b = malloc(10);
printf("please give me an integer");
scanf("%d",&b);
}
void main(){
FILE *fp;
int*ch = NULL;
from_user(ch);
fp = fopen("bfile.txt","w");
if (fp == NULL){
printf("the file did not open");
}
else {
printf("this is what you entered %d",*ch);
fprintf(fp,"%d",*ch);
fclose(fp);
free(ch);
}
}
Am I wrong or is the documentation not explaining this correctly? thanks.

from_user() is not implemented correctly.
The pointer that you create in from_user() will not be passed back to the calling function. To do that, you need a double pointer, or to pass by reference.
In your code, you pass a int ** to scanf(), while it is expecting a variable of int *.
Here's a working implementation:
void from_user(int **b){
*b = malloc(sizeof(int));
printf("please give me an integer");
scanf("%d", *b);
}
int main() {
int *ch;
from_user(&ch);
}
Your File IO
That part is all fine. It's just the value of ch that is broken.

a much simpler from_user implementation
int from_user(){
int i;
printf("please give me an integer");
scanf("%d", &i);
return i;
}
and in main
int ch = from_user();
...
printf("this is what you entered %d",ch);
fprintf(fp,"%d",ch);

Simplest fix to your own code, you don't need to use double pointers, just allocate the memory in main and pass the pointer to your function, like this:
Remove b = malloc(10);
Remove the & before b in scanf
Change int*ch = NULL; to int *ch = malloc(sizeof(int));
Done. Why does it matter where we allocate the memory? See my more detailed answer here: pointer of a pointer in linked list append
Oh and you should move free(ch) out from the else statement.

Related

Writing a character to a file in C (mbed)?

This is my code C/C++ code for writing a character to a file.
#include "mbed.h"
Serial pc(USBTX, USBRX);
char c;
char *cha = &c;
int main() {
FILE* WriteTo = fopen("/local/yourtext.txt", "w");
pc.printf("Write something and then press enter when finished...\n\r");
while (c != '\n') {
c = pc.getc();
pc.printf(cha);
fputc(c, WriteTo);
}
fclose(WriteTo);
pc.printf("File write successfull.\n\r");
}
The problem is that it doesn't work on my LPC1768. It only takes in one character and then I am unable to type anymore. I tried some other ways but none of the ways I tried allowed me to write to a file.
I'd like to also know if getc() empties out after I use putc. Does it have a limitation on the amount of characters I can write?
pc.printf(cha);
printf needs format argument to be null terminated char *.
But you are passing non null terminated char * thus by invoking undefined behavior.
Use:
pc.printf("%c", *cha); //Or pc.printf("%c", c);

C, C++ extract struct member from binary file

I'm using the following code to extract a struct member from a binary file.
I'm wondering why this prints out multiple times? when there is only one ID record, and only one struct in the file. I need to access just this member, what is the best way to do it?
I don't really understand what the while loop is doing? Is it testing for whether the file is open and returning 1 until that point?
Why use fread inside the while loop?
Does the fread need to be set to the specific size of the struct member?
Is the printf statement reading the binary and outputting an int?
FILE *p;
struct myStruct x;
p=fopen("myfile","rb");
while(1) {
size_t n = fread(&x, sizeof(x), 1, p);
if (n == 0) {
break;
}
printf("\n\nID:%d", x.ID); // Use matching specifier
fflush(stdout); // Insure output occurs promptly
}
fclose(p);
return 0;
The struct looks like this:
struct myStruct
{
int cm;
int bytes;
int ID;
int version;
char chunk[1];
}
Not really an answer but to answer a comment.
Just do
FILE *p = fopen("myfile","rb");
struct myStruct x;
size_t n = fread(&x, sizeof(x), 1, p);
if (n != 1) {
// Some error message
} else {
printf("\n\nID:%d\n", x.ID);
}
...Do as you wish with the rest of the file
I'm wondering why this prints out multiple times? when there is only one ID record, and only one struct in the file.
It won't! So if you have multiple prints the likely explanation is that the file contains more than just one struct. Another explanation could be that the file (aka the struct) was not saved in the same way as you use for reading.
I need to access just this member, what is the best way to do it?
Your approach looks fine to me.
I don't really understand what the while loop is doing?
The while is there because the code should be able to read multiple structs from the file. Using while(1) means something like "loop forever". To get out of such a loop, you use break. In your code the break happens when it can't read more structs from the file, i.e. if (n == 0) { break; }
Is it testing for whether the file is open and returning 1 until that point?
No - see answer above.
Why use fread inside the while loop?
As above: To able to read multiple structs from the file
Does the fread need to be set to the specific size of the struct member?
Well, fread is not "set" to anything. It is told how many elements to read and the size of each element. Therefore you call it with sizeof(x).
Is the printf statement reading the binary and outputting an int?
No, the reading is done by fread. Yes, printf outputs the decimal value.
You can try out this code:
#include <stdio.h>
#include <unistd.h>
struct myStruct
{
int cm;
int bytes;
int ID;
int version;
char chunk[1];
};
void rr()
{
printf("Reading file\n");
FILE *p;
struct myStruct x;
p=fopen("somefile","rb");
while(1) {
size_t n = fread(&x, sizeof(x), 1, p);
if (n == 0) {
break;
}
printf("\n\nID:%d", x.ID); // Use matching specifier
fflush(stdout); // Insure output occurs promptly
}
fclose(p);
}
void ww()
{
printf("Creating file containing a single struct\n");
FILE *p;
struct myStruct x;
x.cm = 1;
x.bytes = 2;
x.ID = 3;
x.version = 4;
x.chunk[0] = 'a';
p=fopen("somefile","wb");
fwrite(&x, sizeof(x), 1, p);
fclose(p);
}
int main(void) {
if( access( "somefile", F_OK ) == -1 )
{
// If "somefile" isn't there already, call ww to create it
ww();
}
rr();
return 0;
}
Answers in-line
I'm wondering why this prints out multiple times? when there is only one ID record, and only one struct in the file. I need to access just this member, what is the best way to do it?
The file size is 2906 bytes and fread is only reading sone 17 bytes at a time, and this goes on in a loop
I don't really understand what the while loop is doing? Is it testing for whether the file is open and returning 1 until that point?
The total number of elements successfully read is returned by fread
Why use fread inside the while loop?
In this case while is not necessary. just one fread is enough. Fread is sometimes used in a while loop when input from some other source like UART is being processed and the program has to wait for the said number of bytes t be read
Does the fread need to be set to the specific size of the struct member?
No. Reading the entire struct is better
Is the printf statement reading the binary and outputting an int?
No

How to get the return value between two different c++ program using Visual Studio 2005

Now, I have two programs A and B. Program A uses system() to execute program B.
But, the program B uses writing file way to return its execute result.
Has program A a better way to get the return value of program B?
For example
In program A
int main(){
system("B.exe");
readFile(finePath);
//do something
return 0;
}
In program B
int main(){
char temp[1024];
//do something
writeFile(temp);
return 0;
}
Pipes are a relatively simple, cross-platform way to do this without creating temporary files all over the place and having to deal with the additional issues that potentially arise from doing that.
static string pcommand(const string& cmd)
{
FILE* stream = _popen(cmd.c_str(), "r");
string data;
if (stream)
{
while (!feof(stream))
{
const int buffer_size = 256;
char buffer[buffer_size];
if (fgets(buffer, buffer_size, stream))
data.append(buffer);
}
_pclose(stream);
}
return data;
}
int main()
{
string 'str' = pcommand("dir");
// 'str' now contains the results sent to stdout
}
Method 1.
Try using the ERRORLEVEL system variable to check the return value of any running program.
Note:
ERRORLEVEL is a system variable so use it as such... ;)
Method 2.
You can use Process.ExitCode property.

How to reverse a user input without using array or any library function(any function for reversing)?

Let me clear you first that I'm not a college student and this is not my home assignment. I am just curious to know the solution of this question which was once asked to me. I think this is a nice and tricky question which I feel worth sharing.The question was--
How do you input a string(said in general sense, independent of programming) from a user and print reverse of it in C/C++ without using array or any library function for reversing the user input?
I am unable to break-into this. Help please
Note: Members are marking it as a duplicate for this question. But All answers to this are either using library functions or using a pointer to char array(char *). None of them is allowed in my case. Please review it once again
You can try recursion.
void print_reverse_str() {
int c = getchar();
if (c != EOF) {
print_reverse_str();
putchar(c);
}
}
Technically this is impossible because a string is a char array in c and an object representing a char array in c++.
I hope you meant not using arrays directly.
So try this pointer based solutions :
void strrev(char *str)
{
if( str == NULL )
return;
char *end_ptr = &str[strlen(str) - 1];
char temp;
while( end_ptr > str )
{
temp = *str;
*str++ = *end_ptr;
*end_ptr-- = temp;
}
}

Can't write an integer into a binary file C++

This is basically the part of the code that i used to store the entire file, and works well ... but when i tryed to store a integer bigger than 120 or something like that the program writes seems like a bunch of trash and not the integer that i want. Any tips ? I am an college student and dont have a clue whats happening.
int* temp
temp = (int*) malloc (sizeof(int));
*temp = atoi( it->valor[i].c_str() );
//Writes the integer in 4 bytes
fwrite(temp, sizeof (int), 1, arq);
if( ferror(arq) ){
printf("\n\n Error \n\n");
exit(1);
}
free(temp);
I've already checked the atoi part and it really returns the number that I want to write.
I changed and added some code and it works fine:
#include <iostream>
using namespace std;
int main()
{
int* temp;
FILE *file;
file = fopen("file.bin" , "rb+"); // Opening the file using rb+ for writing
// and reading binary data
temp = (int*) malloc (sizeof(int));
*temp = atoi( "1013" ); // replace "1013" with your string
//Writes the integer in 4 bytes
fwrite(temp, sizeof (int), 1, file);
if( ferror(file) ){
printf("\n\n Error \n\n");
exit(1);
}
free(temp);
}
Make sure you are opening the file with the correct parameters, and that the string you give to atoi(str) is correct.
I checked the binary file using hex editor, after inputting the number 1013.
int i = atoi("123");
std::ofstream file("filename", std::ios::bin);
file.write(reinterpret_cast<char*>(&i), sizeof(i));
Do not use pointers here.
Never use malloc / free in C++.
Use C++ file streams, not C streams.