Program crashes after reading data from file using fscanf - c++

I have written a simple program to read the content of a text file and I compiled it with cl.exe (visual studio compiler). The program compiles, and when I run it, it starts normally and the moment it goes past the reading and printing of the data it crashes brutally... Here's my code :
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <fstream>
#include <string>
int main (int argc, char *argv[])
{
char filename[256];
char d1[9];
char d2[8];
if (argc > 1) //lecture de l'argument
strcpy(filename, argv[1]);
else {
printf("Usage: read_file");
return 0;
}
FILE *f = fopen(filename, "r");
if (f == NULL) {
printf("Cannot find file \'%s\'\n", filename);
return 0;
}
printf("file opened\n");
rewind(f);
fscanf(f, "%s %s", d1, d2);
printf("%s %s",d1,d2);
fclose(f);
return 1;
}
When I compile it with gcc it works just fine however. The thing is, I need this to run with visual studio compiler...

First of all, you should have posted your input example.
Anyway, as other people have stated d1 and d2 are too small and are not storing the C-Null terminator. Just make them larger (d1[10], d2[9]).
Finally, you are programming in c++ so therefore I would recommend using the c++ libraries. Your code would be simpler and would not mix c and c++.
Best regards.

Related

read and write doesn't work in named pipes c++

Please excuse my English, its not the best. Thank you.
I am suppose to write 2 simple programs, which are suppose to enable two communication between processes in/with named pipes(C++).
Each code search through the directory and (name of the directory is suppose to be inputed by a user) search for FIFO file type. After finding a file, first code opens to read, second code opens to write. If process can't find a file, then it will ask user to input a new path.
First code write the message in the terminal(stdin) and send it through the pipe to second process. Second process read the message from the pipe and shows it in terminal(stdout). Both processes are suppose to end after reading message from stdin and sending a statement 'END';
I am still learning and trying to find more about named pipes so for now I could only write some basics programs(just to read and write) but still I don't understand why both of them doesn't work.
Can You tell me what is wrong with my codes? Thank You.
here is my code for read
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
char sentence [256];
int fp, numr ,numop;
umask(0);
fp = mkfifo("myfifo", S_IFIFO|0666);
if(fp < 0)
{
printf("Cant make a file\n");
return 1;
}
numop = open("myfifo",O_RDONLY);
if(numop < 0)
{
printf("Cant open the file\n");
return 1;
}
numr = read(fp,&sentence,sizeof(sentence));
if( numr < 0)
{
printf("Cant read the message\n");
return 1;
}
fgets(sentence,256,stdin);
printf("Message: %s\n",sentence);
close(fp);
return 0;
}
here is for write
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int fd , numw;
char sentence [256];
fd = open("myfifo", O_WRONLY);
if(fd < 0)
{
printf("Can't open a file\n");
return 1;
}
printf ("Enter the message : ");
fgets(sentence,250,stdin);
numw = write(fd,sentence,strlen(sentence)+1);
if(numw < 0)
{
printf("Can write the message");
return 1;
}
close(fd);
return 0;
}
can you tell me what am I doing wrong?

Does't work fopen_s(&file, "filename", mode) in visual studio 2019 C_language

So this is my first question here. If you could help me, that would be much appreciated. This code is about my thesis. I'm trying to write to a file and it works but trying to read another file is not reading. I can't make it work. "file does not open" appears on the screen. Help me please, for read to file.
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
FILE* myfile;
errno_t errorcode = fopen_s(&myfile, "output.txt", "w");
if (myfile == NULL)
{
printf("Error");
}
FILE* data;
errno_t err = fopen_s(&data, "C:\SA\input.txt", "r");
//errno_t err = fopen_s(&data, "input.txt", "r");
if(data==NULL)
{
printf("file does not open");
}
return 0;
getchar();
}
The original code posted had 2 major issues:
"C:\SA\input.txt" should be "C:\\SA\\input.txt" or simply "C:/SA/input.txt". Microsoft's legacy systems use \ as a path separator which must be escaped in C strings as \\ (and in many other languages too). The traditional path separator on POSIX systems is / and it is also supported in Windows.
if(data==NULL); is a test with an empty statement, hence nothing happens.
Note that you should not use C++ headers such as <iostream> in a C program.
Here is a simplified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *myfile;
errno_t err = fopen_s(&myfile, "output.txt", "w");
if (err) {
fprintf(stderr, "Cannot open file %s: %s\n",
"output.txt", strerror(err));
return 1;
}
FILE *data;
err = fopen_s(&data, "C:\\SA\\input.txt", "r");
if (err) {
fprintf(stderr, "Cannot open file %s: %s\n",
"C:\\SA\\input.txt.txt", strerror(err));
return 1;
}
getchar(); // keep terminal window open
return 0;
}

The program is not opening to me a shell

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv){
FILE *fp = fopen("1.pass", "r");
struct {char pass[20], msg_err[20];} pwfile = {{0}};
char ptr[0];
if(!fp || argc != 2)
return -1;
fread(pwfile.pass, 1, 20, fp);
pwfile.pass[19] = 0;
ptr[atoi(argv[1])] = 0;
fread(pwfile.msg_err, 1, 19, fp);
fclose(fp);
if(!strcmp(pwfile.pass, argv[1])) {
setuid(0);
execl("/bin/sh", "sh", 0);
} else
puts(pwfile.msg_err);
return 0;
}
Hello there.
I give on input to the program a password. The program checks this password, which is in 1.pass. If all is correct - opens to me a shell, if it not correct - print ACCESS DENIED.
In my cases, it didn't open shell up to me, I don't know why. Any ideas what I missed?
char ptr[0];
ptr[atoi(argv[1])] = 0;
This is not legal C++, as there are no zero sized arrays in C++. Even if some C++ compilers offer zero sized arrays as an extension, this particular code doesn't do anything useful, and may or may not format your hard disk.

How to store the system command output in a variable?

I am executing a system() function which returns me a file name. Now I dont want to display the output on the screen(ie the filename) or pipe to a newfile. I just want to store it in a variable. is that possible? if so, how?
thanks
A single filename? Yes. That is certainly possible, but not using system().
Use popen(). This is available in c and c++, you've tagged your question with both but are probably going to code in one or the other.
Here's an example in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fpipe;
char *command = "ls";
char c = 0;
if (0 == (fpipe = (FILE*)popen(command, "r")))
{
perror("popen() failed.");
exit(EXIT_FAILURE);
}
while (fread(&c, sizeof c, 1, fpipe))
{
printf("%c", c);
}
pclose(fpipe);
return EXIT_SUCCESS;
}
Well,There is one more easy way by which you can store command output in a file which is called redirection method. I think redirection is quite easy and It will be useful in your case.
so For Example this is my code in c++
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
system("ls -l >> a.text");
return 0;
}
Here redirection sign easily redirect all output of that command into a.text file.
You can use popen(3) and read from that file.
FILE *popen(const char *command, const char *type);
So basically you run your command and then read from the FILE returned. popen(3) works just like system (invokes the shell) so you should be able to run anything with it.
Here is my C++ implementation, which redirects system() stdout to a logging system. It uses GNU libc's getline(). It will throw an exception if it can't run the command, but will not throw if the command runs with non-zero status.
void infoLogger(const std::string& line); // DIY logger.
int LoggedSystem(const string& prefix, const string& cmd)
{
infoLogger(cmd);
FILE* fpipe = popen(cmd.c_str(), "r");
if (fpipe == NULL)
throw std::runtime_error(string("Can't run ") + cmd);
char* lineptr;
size_t n;
ssize_t s;
do {
lineptr = NULL;
s = getline(&lineptr, &n, fpipe);
if (s > 0 && lineptr != NULL) {
if (lineptr[s - 1] == '\n')
lineptr[--s ] = 0;
if (lineptr[s - 1] == '\r')
lineptr[--s ] = 0;
infoLogger(prefix + lineptr);
}
if (lineptr != NULL)
free(lineptr);
} while (s > 0);
int status = pclose(fpipe);
infoLogger(String::Format("Status:%d", status));
return status;
}

How to write to a memory buffer with a FILE*?

Is there any way to create a memory buffer as a FILE*. In TiXml it can print the xml to a FILE* but i cant seem to make it print to a memory buffer.
There is a POSIX way to use memory as a FILE descriptor: fmemopen or open_memstream, depending on the semantics you want: Difference between fmemopen and open_memstream
I guess the proper answer is that by Kevin. But here is a hack to do it with FILE *. Note that if the buffer size (here 100000) is too small then you lose data, as it is written out when the buffer is flushed. Also, if the program calls fflush() you lose the data.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *f = fopen("/dev/null", "w");
int i;
int written = 0;
char *buf = malloc(100000);
setbuffer(f, buf, 100000);
for (i = 0; i < 1000; i++)
{
written += fprintf(f, "Number %d\n", i);
}
for (i = 0; i < written; i++) {
printf("%c", buf[i]);
}
}
fmemopen can create FILE from buffer, does it make any sense to you?
I wrote a simple example how i would create an in-memory FILE:
#include <unistd.h>
#include <stdio.h>
int main(){
int p[2]; pipe(p); FILE *f = fdopen( p[1], "w" );
if( !fork() ){
fprintf( f, "working" );
return 0;
}
fclose(f); close(p[1]);
char buff[100]; int len;
while( (len=read(p[0], buff, 100))>0 )
printf(" from child: '%*s'", len, buff );
puts("");
}
C++ basic_streambuf inheritance
In C++, you should avoid FILE* if you can.
Using only the C++ stdlib, it is possible to make a single interface that transparently uses file or memory IO.
This uses techniques mentioned at: Setting the internal buffer used by a standard stream (pubsetbuf)
#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>
/* This can write either to files or memory. */
void write(std::ostream& os) {
os << "abc";
}
template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> > {
ostreambuf(char_type* buffer, std::streamsize bufferLength) {
this->setp(buffer, buffer + bufferLength);
}
};
int main() {
/* To memory, in our own externally supplied buffer. */
{
char c[3];
ostreambuf<char> buf(c, sizeof(c));
std::ostream s(&buf);
write(s);
assert(memcmp(c, "abc", sizeof(c)) == 0);
}
/* To memory, but in a hidden buffer. */
{
std::stringstream s;
write(s);
assert(s.str() == "abc");
}
/* To file. */
{
std::ofstream s("a.tmp");
write(s);
s.close();
}
/* I think this is implementation defined.
* pusetbuf calls basic_filebuf::setbuf(). */
{
char c[3];
std::ofstream s;
s.rdbuf()->pubsetbuf(c, sizeof c);
write(s);
s.close();
//assert(memcmp(c, "abc", sizeof(c)) == 0);
}
}
Unfortunately, it does not seem possible to interchange FILE* and fstream: Getting a FILE* from a std::fstream
You could use the CStr method of TiXMLPrinter which the documentation states:
The TiXmlPrinter is useful when you
need to:
Print to memory (especially in non-STL mode)
Control formatting (line endings, etc.)
https://github.com/Snaipe/fmem is a wrapper for different platform/version specific implementations of memory streams
It tries in sequence the following implementations:
open_memstream.
fopencookie, with growing dynamic buffer.
funopen, with growing dynamic buffer.
WinAPI temporary memory-backed file.
When no other mean is available, fmem falls back to tmpfile()