Does not work _cgets. Identifier not found - c++

I am trying to compile the following code in visual studio 2019:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string>
int main()
{
char buffer[5];
char* p;
buffer[0] = 3;
p = _cgets(buffer); // problem with _cgets
printf("\ncgets read %d symbols: \"%s\"\n", buffer[1], p);
printf("A pointer is returned %p, buffer[2] on %p\n", p, &buffer);
return 0;
}
But I see the following error:
main.cpp(11,9): error C3861: '_cgets': identifier not found

_cgets is no longer available, use _cgets_s instead:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string>
int main()
{
char buffer[5];
size_t sizeRead;
auto error = _cgets_s(buffer, &sizeRead);
printf("\ncgets read %zu symbols: \"%s\"\n", sizeRead, buffer);
return 0;
}
Or the much simpler c++ code:
#include <iostream>
#include <string>
int main()
{
std::string buffer;
std::getline(std::cin, buffer);
std::cout << "read " << buffer.size() << " characters \"" << buffer << "\"\n";
}

Related

Having issues with mmap from within a function

I'm trying to write a function that has mmap within it, however when I try to access the memory from main(), it gets a segfault. Does anyone have any idea why?
Please ignore the MPI headers - it's for the later part of the project. I have commented out the mprotect line to see that it is an mmap fault as opposed to the handler not necessarily working
net_map.cpp:
#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "net_map.h"
using namespace std;
void handler(int sig, siginfo_t* info, void* other)
{
void* address = info->si_addr;
cout << "\nSegfault Detected! [Address: " << address << "]\n" << endl;
int unprotectresult = mprotect(address, SIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
if (unprotectresult == 0)
{
cout << "\nSuccessful mprotect (memory unprotected)!\n" << endl;
}else
{
cout << "\nMprotect unsuccessful\n" << endl;
}
}
void netmap (char filename[], char* mapped)
{
int file;
file = open(filename, O_RDWR);
mapped = (char*) mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0);
if (mapped == MAP_FAILED)
{
cout << "\nMap Failed!" << endl;
}
cout << mapped << endl;
}
main.cpp
#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <unistd.h>
#include <array>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <array>
#include "net_map.h"
using namespace std;
int main(int argc, char* argv[])
{
struct sigaction segaction;
memset(&segaction, 0, sizeof(segaction));
segaction.sa_flags = SA_SIGINFO;
sigemptyset(&segaction.sa_mask);
segaction.sa_sigaction = handler;
sigaction(SIGSEGV, &segaction, NULL);
int i;
char* mapped;
networkpage sheet;
char filename[] = "hello.txt";
netmap(filename, mapped);
sheet.address = (void*)mapped;
cout << "\nAddress: " << sheet.address << endl;
//mprotect(sheet.address, SIZE, PROT_NONE);
memcpy(sheet.address, "k", 1);
munmap(sheet.address, SIZE);
return 0;
}

how to correctly write a protobuf message in text format to a file

My question is how to correctly write a protobuf message in text format to a file. In the program below I create a NetParameter object which is a message
field in message field in caffe.proto.
When I call print() and PrintToString() they return failure.
I can print the mesaage on the console with printf("%s", data.c_str()); but notting is written to file?
#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include <string>
#include "caffe.pb.h"
#include <iostream>
#include <caffe/caffe.hpp>
using namespace std;
using google::protobuf::Message;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::TextFormat;
int main()
{
caffe::NetParameter param;
const char *filename = "./test.prototxt";
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1)
cout << "File not found: " << filename;
google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);
param.set_name("AlexNet");
param.add_input_dim(0);
param.add_input_dim(1);
param.add_input_dim(2);
param.set_input_dim(0, 3);
param.set_input_dim(1, 3);
param.set_input_dim(2, 3);
std::string data;
bool success = google::protobuf::TextFormat::PrintToString(param, &data);
std::cout << "bool is " << success << std::endl;
printf("%s", data.c_str());
bool success1 = google::protobuf::TextFormat::Print(param, output);
std::cout << "bool is " << success << std::endl;
close(fd);
return 0;
}

strerror_s,strcpy_s,localtime_s,sprintf_s not declared in this scope?

I have written a cross-platform code gives a current date(mm/dd/yy) and time(hh/mm/ss) and complete date(yyyymmdd), This code works in windows(MSVS2015) but not working in Linux(GCC 4.8.5).
My code is
#include <iostream>
#ifdef WIN32
#include <windows.h>
#else
#include <cerrno>
#endif
#ifdef WIN32
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#endif
#include <ctime>
#include <bitset>
#include <cstdlib> /*atol*/
#include <iomanip>
#include <stdexcept>
#include <cstring>
#include <cstdio>
#include <fstream>
using namespace std;
template <size_t size>
void GetNowDateTime(char(&c_date)[size], char(&c_time)[size])
{
time_t t;
struct tm now;
strcpy_s(c_date, "00/00/00");
strcpy_s(c_time, "00:00:00");
time(&t);
if (localtime_s(&now, &t) != 0) return;
char temp[3];
sprintf_s(temp, "%.2d", now.tm_mon + 1);
memcpy(c_date, temp, 2);
sprintf_s(temp, "%.2d", now.tm_mday);
memcpy(c_date + 3, temp, 2);
sprintf_s(temp, "%.2d", now.tm_year - 100);
memcpy(c_date + 6, temp, 2);
sprintf_s(temp, "%.2d", now.tm_hour);
memcpy(c_time, temp, 2);
sprintf_s(temp, "%.2d", now.tm_min);
memcpy(c_time + 3, temp, 2);
sprintf_s(temp, "%.2d", now.tm_sec);
memcpy(c_time + 6, temp, 2);
}
int GetToday(void)
{
time_t t;
struct tm now;
time(&t);
if (localtime_s(&now, &t) != 0) return 0;
return (now.tm_year + 1900) * 10000 + (now.tm_mon + 1) * 100 + now.tm_mday;
}
bool OpenOuputFile(ofstream& outputFile)
{
char buf[1024];
#ifdef WIN32
strcpy_s(buf, "C:\\Myfolder\\output.txt");
#else
strcpy_s(buf, "/home/myfolder/output.txt");
#endif
outputFile.open(buf, ios::out);
if (!outputFile)
{
char szErrorMsg[1024];
strerror_s(szErrorMsg, errno);
cout << "Unable to open input file. " << buf << " Error:" << szErrorMsg << endl;
return 0;
}
return 1;
}
//Here is my main function
int main()
{
char today[9];
char time[9];
ofstream outputFile;
GetNowDateTime(today, time);
int yyyymmdd = GetToday();
if (OpenOuputFile(outputFile))
{
outputFile << "GetNowDateTime functions given is:-\t" << today << "\t" << time << endl;
outputFile << "GetToday Function given is:-\t" << yyyymmdd << endl;
}
else
cout << "No output file written" << endl;
return 0;
}
Errors in Linux is
TimeDate.cpp: In function ‘void GetNowDateTime(char (&)[size], char (&)[size])’:
TimeDate.cpp:34:26: error: there are no arguments to ‘localtime_s’ that depend on a template parameter, so a declaration of ‘localtime_s’ must be available [-fpermissive]
if (localtime_s(&now, &t) != 0) return;
TimeDate.cpp:36:40: error: there are no arguments to ‘sprintf_s’ that depend on a template parameter, so a declaration of ‘sprintf_s’ must be available [-fpermissive]
imeDate.cpp: In function ‘int GetToday()’:
TimeDate.cpp:55:26: error: ‘localtime_s’ was not declared in this scope
if (localtime_s(&now, &t) != 0) return 0;
TimeDate.cpp:74:31: error: ‘strerror_s’ was not declared in this scope
strerror_s(szErrorMsg, errno);
TimeDate.cpp:31:29: error: ‘strcpy_s’ was not declared in this scope
strcpy_s(c_date, "00/00/00");
This program runs on (windows )visual studio 2015 and(Linux) GCC 4.8.5.
I included all required headers but It showing errors when compiling in Linux.
why above errors showing in Linux, Please tell me.
strcpy_s and friends were Microsoft extensions to c, they were standardised in C11. GCC 4.8.5 doesn't support them and newer versions probably don't either When will the safe string functions of C11 be part of glibc?
sprintf_s and the other _s functions are not part of Standard C++. Your program will be restricted to compilers which have those functions as a non-standard extension.

Visual Studio 2015: Getting "non standard syntax, use '&' to create a pointer to member" error

Super confused as to what is throwing the error when I try to compile my code. I'm currently trying to test a function I wrote by printing out the values it should extract from a file.
gameboard.cpp
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "error.h"
using namespace std;
int boardDim(ifstream & inputFile, unsigned int x, unsigned int y) {
inputFile.open; //error is thrown here
if (!(inputFile.is_open())) {
throw fileNotOpen;
}
else {
stringstream output(inputFile.getline); //error is also thrown here
if (output >> x) {
if (output >> y) {
return success;
}
return secBoardVarErr;
}
return firstBoardVarErr;
}
cout << x << endl;
cout << y << endl;
}
gameboard.h
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include <iostream>
using namespace std;
//takes in dimensions of board from file
int boardDim(ifstream &, unsigned int, unsigned int);
#endif !GAMEBOARD_H
main function
#include "stdafx.h"
#include "functions.h"
#include "gamepieces.h"
#include "gameboard.h"
#include "error.h"
int main(int argc, char * argv[])
{
ifstream x("test.txt");
int test = 0;
cout << boardDim(x, 0, 0) << endl;
return success;
}
I'm only testing the function I declared and defined in the gameboard header and source files, so the other included files will be used in the future but have already been tested and are not throwing errors when I compile and run it.
Thank you!
inputFile.open is a function, same with inputFile.getline, so what you have here is a syntactic error. The correct syntax is:
inputFile.open()
and
inputFile.getline()

C++ | Problems with files

I'm pretty new to C++ and I wanted to start working with files so I ended up doing this :
#include <iostream>
#include <string>
#include <cstdlib>
#include <windows.h>
#include <stdexcept>
#include <limits>
#include <Lmcons.h>
#include <fstream>
using namespace std;
void out(string x){x+="\n";cout<<x;}
void outn(){out("");}
void delay(int x){Sleep(x);}
void delayS(int x){Sleep(x*1000);}
void cs(){std::system("cls");}
void UserName(string *x){char username[UNLEN + 1];DWORD size = UNLEN + 1;GetUserName(username, &size);string transition(username);*x=transition;}
//use this synthax in main : char user[20];string username(user);UserName(&username);
using namespace std;
int main()
{
char user[20];string username(user);UserName(&username);
out(username);
delayS(2);
cs();
string beginning="C:\\Users\\" ;
string path;
string ending="\\Desktop\\";
string filename;
out("file name = ");
cin>>filename;
path+=beginning;
out(path);
delayS(2);
path+=username;
out(path);
delayS(2);
path+=ending;
out(path);
delayS(2);
path+=filename;
out(path);
delayS(2);
ofstream file;
try{
file.open(path ,ios::in);
if(!file.is_open()){throw 404;}
else{
file.open(path,ios::out|ios::app);
file<<"\n";
file<<"lol";}
}catch(int x){cout<<"Error "<<x<<" : file not found";}
return 0;
}
Which result in this error (line 59) :
" no matching function for call to 'std::basic_ofstream::open(std::string&, std::_Ios_Openmode)' "
image of error : https://imgur.com/YVBHDzq
May I have some help ?
EDIT: I'm using Codeblocks 16.01
In pre-C++11, you need to pass a const char* to ofstream::open() as the first parameter:
file.open( path.c_str(), ios::in );