I have some problems with fopen() for c-string - c++

I have a file name stored as c-string. I need to open the file and count lines in it.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
char str[] = "myfile.txt";
FILE* file = fopen(str, "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}
evrething works just fine if I use fopen("myfile.txt", "r") insted. How to make it work with a c-string file name.

please use string.c_str()
int main() {
string path = "myfile.txt";
FILE* file = fopen(path.c_str(), "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}

Related

i have a program that takes input a string that's called search which is the target and i want to search in the csv file if the "search" is there

#include <stdio.h>
#include <string.h>
void myFgets(char str[], int n);
int main(int argc, char** argv)
{
if (argc < 2)
{
printf("Usage: csv <csv file path>\n");
return 1;
}
else
{
char ch = ' ', search[100], dh = ' ';
int row = 1;
printf("Enter value to search: ");
myFgets(search, 100);
FILE* fileRead = fopen(argv[1], "r");
if (fileRead == NULL)
{
printf("Error opening the file!\n");
return 1;
}
while ((ch = (char)fgetc(fileRead)) != EOF)
{
char str[100];
int i = 0, pos = ftell(fileRead);
while ((dh = (char)fgetc(fileRead)) != ',')
{
str[i] = dh;
i++;
}
fseek(fileRead, pos + 1, SEEK_SET);
if (strstr("\n", str) != NULL)
{
row++;
}
if (strstr(search, str) != NULL)
{
printf("Value was found in row: %d\n", row);
break;
}
}
}
getchar();
return 0;
}
/*
Function will perform the fgets command and also remove the newline
that might be at the end of the string - a known issue with fgets.
input: the buffer to read into, the number of chars to read
*/
void myFgets(char* str, int n)
{
fgets(str, n, stdin);
str[strcspn(str, "\n")] = 0;
}
in line 39 im getting an error but idk why it seems like im doing everything fine
im trying to loop through the rows and split them by the ',' so i could check if search == to it but its not wokring
im using function strstr to compare 2 strings with each other it works fine and all but the only problem is at the dh
i did fseek after the dh so i dont write in the wrong place in the ch loop
You forgot to terminate the string.
while ((dh = (char)fgetc(fileRead)) != ',')
{
str[i] = dh;
i++;
}
str[i] = '\0'; /* add this to terminate the string */
Also it looks like if (strstr(search, str) != NULL) should be if (strstr(str, search) != NULL) to search for the value to search from the contents of the file.

Not able to read utf-8 characters from the file in C++ from input file

I would like to read utf-8 characters from a file in C++ program in Linux platform. In the fgets() function it returns junk characters in place of utf-8 character. input.txt has text triuöschen
#include <stdio.h>
#include <string>
int main()
{
FILE* fpointer = NULL;
std::string szFileData = "";
char cLine[1025] = "\0";
int iTrailingPointer = 0;
try {
const char* pcFileName = "input.txt";
//OPEN THE FILE IN READ MODE...
fpointer = fopen(pcFileName, "r");
if (fpointer == NULL)
{
printf("\n Error reading file %s", szFileData.c_str());
return 0;
}
//READ THE FILE DATA TILL THE END OF FILE...
while (!feof(fpointer))
{
memset(cLine, '\0', 1024);
fgets(cLine, 1024, fpointer);
iTrailingPointer = (int)strlen(cLine) - 1;
//REMOVE TRAILING SPACES AND NEWLINES...
while (cLine[iTrailingPointer] == '\n' || cLine[iTrailingPointer] == ' ' ||
cLine[iTrailingPointer] == '\t')
{
iTrailingPointer--;
}
cLine[iTrailingPointer + 1] = '\0';
szFileData = szFileData + cLine;
printf("\n szFileData: %s", szFileData.c_str());
}
fclose(fpointer);
}
catch (...) {
}
return 0;
}

Read file with variable name C++

I am trying to open a different file for different levels and need a variable name to do so. I tried the following but gave the error: "no suitable conversion from string to const char"
void loadMap(){
//string levelname;
//levelname = '../Levels/Level' + level;
FILE *file;
file = fopen("../Levels/Level" + level + ".txt", "r"); //THIS LINE IS GIVING THE ERROR
char section[80];
int index = 0;
int x = 0;
int y = 0;
while(true){
fscanf(file, "%s", section);
if(strcmp(section, "[Victor]") == 0){
while(true){
fscanf(file, "%d%d%d", &index, &x, &y);
if(index == -1){
break;
}
victor.x = x;
victor.y = y;
}
}
...
...
//more code
First of all, you should be using std::ifstream, it's the C++ way(tm).
Secondly, concatenation of strings should be done using std::stringstream from the header sstream, here's an example of how this could be accomplished:
#include <iostream>
#include <sstream>
#include <fstream>
int main() {
std::string level = "test";
std::stringstream ss;
ss<<"../Levels/Level"<<level<<".txt";
std::ifstream file(ss.str());
if(!file.is_open()) {
// error
} else {
// continue
}
}
"../Levels/Level" + level + ".txt" is evaluated to string object but fopen() takes const char* as first argument. You can fix it in following way:
fopen(("../Levels/Level" + level + ".txt").c_str(), "r");
FILE *file;
char buf[50];
snprintf(buf, sizeof(buf),"%s%d.txt","../Levels/Level",level);
file = fopen(buf, "r");

Source File Compiling and Command

I am new to programming and was able to compile the following source code in C++ using Visual Studio, but when I put the command that came with the source file foo < RTP300.cfg > text.cfg nothing happens. This command is supposed to generate a text file from a router configuration file. Where should the RTP300.cfg file that the command is pointing to be located? Any other info that can help would be greatly appreciated. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int decode(unsigned char);
int
decode(unsigned char ch)
{
ch = ~((ch << 2) | ((ch & 0xC0) >> 6));
if (ch) {
if (isprint(ch)) {
return ch;
} else {
return ' ';
}
}
return '\n';
}
int
main(int argc, char *argv[])
{
int ch;
FILE *fp;
if (argc < 2) {
fp = stdin;
} else {
if (NULL == (fp = fopen(argv[1], "r"))) {
fprintf(stderr, "Error: Cannot open file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
}
while (EOF != (ch =fgetc(fp))) {
fputc(decode(ch), stdout);
}
return EXIT_SUCCESS;
}

Outputting from file one line at a time

I'm trying to output text from a file one line at a time. I'm currently hardcoding it and I have this so far:
int main(int argc, char *argv[])
{
int x;
int k;
int limit = 5;
FILE *file;
file = fopen("C:\\Documents and Settings\\jon\\My Documents\\Visual Studio 2008\\Projects\\Project1\\Assignment8_2\\Debug\\TestFile1.txt", "r");
if (file == NULL) {
perror("Error");
}
for (k = 1; k <= limit; k++) {
while ((x = fgetc(file)) != '\n') {
printf("%c", x);
}
}
fclose(file);
}
I was wondering where in the code above, if at all, I can check for EOF. I assume I need to do that, but not sure why. Still learning.... Thanks!
If you can bound the maximum length of a line, fgets may be a better way to read each line; but since you mention C++, you might consider using, instead, getline (caveat: fgets also put the \n in the buffer it fills, getline doesn't). Both make easy to check for end of file (fgets returns NULL on eof, getline sets the eofbit on its istream argument, which it also returns).
Maybe you can try this:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (inFile >> x) {
sum = sum + x;
}
inFile.close();
cout << "Sum = " << sum << endl;
return 0;
}
fgets() for C, getline() for C++.
C:
#include <stdio.h>
#include <stdlib.h>
// adjust as appropriate
size_t const MAX_LINE_LENGTH = 1024;
int main()
{
FILE * in;
char line[ MAX_LINE_LENGTH ];
if ( ( in = fopen( "test.txt", "r" ) ) == NULL )
{
puts( "Failed to open test.txt." );
return EXIT_FAILURE;
}
while ( fgets( line, MAX_LINE_LENGTH, in ) != NULL )
{
printf( "%s", line );
}
fclose( in );
return EXIT_SUCCESS;
}
C++:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream in( "test.txt" );
std::string line;
while ( getline( in, line ) )
{
std::cout << line << std::endl;
}
in.close();
return 0;
}
you can call feof() to check for EOF or check if the return code for fgetc() matches EOF.
I'm adding both versions to your code although I'm not sure what the loops (especially the outer one) are supposed to do, but within the context of your sample, EOF checking would look like this..
/* EOF would now terminate both loops, using feof() and fgetc() return to check EOF */
for (k = 1; k <= limit && !feof(file); k++) {
while ((x = fgetc(file))!='\n' && x!=EOF) {
printf("%c", x);
}
}
you should check the eof from the output of fgetc:
...
x = fgetc(file);
while (x != '\n' && x != EOF) {
...
fgetc manual there