stream != nullptr visual studio, simply printing values from txt file (C) - c

I am starting to program in Visual Studio (C) and I'm simply trying to print the values in the file, one by one. I can easily do this in my Eclipse version. (Which is the exact same code). My txt file is in project folder as seen here:
https://i.imgur.com/SPjZOrN.png
The code is as follows:
#include <stdio.h>
int main(int argc, char **argv) {
int c;
FILE *file;
const char* file_name = "ECG.txt";
file = fopen(file_name, "r");
int i = 0;
fscanf(file, "%d", &i);
while (!feof(file))
{
printf("%d ", i);
fscanf(file, "%d", &i);
}
fclose(file);
return 0;
}
When I run this, I get the error stream != nullptr how can I fix this?

It is very likely that your program tries to load the file from the directory where your executable resides, and not from that where your source files are (as you intend).
Either place the ECG.txt-file in the target directory or use absolute paths, e.g. "c:/myuser/myproject/ECG.txt";
Always check the result of fopen. If the result is NULL, then the file could not be opened (probably the reason for your runtime error). So the relevant portion of your program could loo as follows:
file = fopen(file_name, "r");
if (file) {
int i = 0;
while (fscanf(file, "%d", &i)==1) {
printf("%d ", i);
}
fclose(file);
} else {
printf("error opening file");
}

Related

Why I cannot read this text file with numerical data from my C program?

I have a text file with 4096 numerical data that I am trying to read with a C source. But, my program does not work at all. Just show "fail to open a file"
Why?
But, if I try another text file, it works.
Please tell me what the problem is!
Heads from two text files are below:
*head of cannot_read.txt
50129.248000000000
50129.248000000000
2193.2479999999996
2193.2479999999996
2961.2479999999996
2577.2479999999996
1809.2479999999996
81.247999999999593
721.24799999999959
1745.2479999999996
*can_read.txt
3.45654675443
1.23536565353
123123.353535
3.45654675443
1.23536565353
123123.353535
3.45654675443
1.23536565353
123123.353535
3.45654675443
My program.
#include <stdio.h>
int main(void)
{
int n, i;
int j;
// float fval[4097];
long double fval[4097];
FILE * fp;
// fp = fopen("/home/changwan/C/can_read.txt","r");
fp = fopen("/home/changwan/C/cannot_read.txt","r");
if(fp==NULL){
puts("fail to open a file!");
return -1;
}
n = 0;
// while (fscanf(fp, "%f", &fval[n++]) !=EOF)
while (fscanf(fp, "%Lf", &fval[n++]) !=EOF)
;
for (i=0; i<n-1; i++)
printf("fval[%d]=%Lf\n", i, fval[i]);
fclose(fp);
return 0;
}
The fopen() function does not support the ~ symbol. Check out the realpath() function and the difference between absolute and relative paths.

How to dump txt file in C?

#include <stdio.h>
int main(void) {
int name;
int arrival_time;
int size;
int ret;
FILE * fp = fopen_s("C:\\NIA\\data.txt", "rt");
while (1)
{
ret = fscanf_s(fp, "%d %d %d", &name, &arrival_time, &size);
if (ret == EOF)
break;
printf("%d %d %d \n", name, arrival_time, size);
}
return 0;
}
I want to dump my txt file to project but errors are coming out. I'm confused about memory initiation and file format, variables, etc. How can I fix this and print values well?
My txt file is :
Your question lacks the most important information: What is going wrong.
When I compile your code, I get errors for fopen_s. (OK, this is mainly because I use gcc ;) )
The manual tells us how this function looks like:
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
This means, you must use it like this:
errno_t err;
FILE *fp;
err = fopen_s(&fp, "C:\\NIA\\data.txt", "rt");
if (err != 0)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
Or you stick to standard functions and use them as you already tried:
FILE *fp;
fp = fopen("C:\\NIA\\data.txt", "rt");
if (fp = NULL)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
You should definitely add checks for all return values. At least for I/O related functions like fopen and scanf.
Also closing your file would be adviseable. While it is only opened in read mode, it will not cause much trouble as it is closed automatically on program termination, but it is surely good style to do it.
An improved version could look like this:
(As you do not scan strings, there is no benefit using MS non-standard function scanf_s)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int name;
int arrival_time;
int size;
FILE * fp = fopen("data.txt", "rt");
if (fp == NULL) {
perror("File data.txt cannot be opened");
exit(1);
}
while (fscanf(fp, "%d %d %d", &name, &arrival_time, &size) == 3)
{
printf("%d %d %d\n", name, arrival_time, size);
}
fclose(fp);
return 0;
}
This prints the content of your data.txt file on the console.
If dumping you txt file means closing the txt file after using it, you can use the following
fclose(fp);
before the return 0;

How to write data to multiple files using arrays of pointers of file in C?

This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}

How to read a file in C from a subdirectory

This is driving me crazy. I want to read from a subdirectory (./method/CoyoteAdapter.java.tk.method.514.5.533.5.bk), but my code crashes at fscan (Bus error):
void readFrag( int **sequence, int& nTokens, char* fragName )
{
FILE *file;
char tmp[200];
strncpy(tmp, &fragName[2], 198);
char szWorkingDirectory[PATH_MAX];
szWorkingDirectory[0] = '\0';
getwd(szWorkingDirectory);
printf("Attempting to open %s/%s\n", szWorkingDirectory, tmp);
file = fopen(tmp, "r");
nTokens = 0;
fscanf(file, "%d", &(*sequence)[nTokens]);
while(!feof (file))
{
fscanf(file, "%d", &(*sequence)[nTokens]);
++nTokens;
}
fclose(file);
}
// maxFragSizes: Each block has its max frag size
void init( int **seq, int& seqSize, int **sub, int& subSize, int **problemSizesPerBlock, char* fragListName )
{
FILE *file;
char line[200];
int* tokens = new int[THREADS_PER_BLOCK-1];
int nTokens = 0;
file = fopen(fragListName, "rt");
while(fgets(line, 200, file) != NULL)
{
readFrag( &(*seq), nTokens, line );
}
fclose(file);
}
However, if I copy the file to my directory, it works. I'm on UNIX (Mac OS). Please help!
Edit: I added the following code, as suggested. The output it ok, but it still doesn't work...
You must have to verify the file pointer. May be file is not found or you don't have sufficient privileges to read it.
file = fopen(fragName, "rt");
if(file==NULL)
{
printf("\nFile not found");
return 0;
}
fscanf(file, "%d", &tmp);
You aren't checking to see if "file" being returned by fopen() is NULL or not before calling fscanf. That's why you are crashing.
As to how to open a file, you may want to call getcwd (getwd) and print the result to see if you are in the parent directory that you think you are in. You probably don't need the "./" prefix in your file path, but I don't think it hurts.
void readFrag( char* fragName )
{
FILE *file;
int tmp;
char szWorkingDir[PATH_MAX];
szWorkingDirectory[0] = '\0';
getwd(szWorkingDirectory);
printf("Attempting to open %s/%s\n", szWorkingDir, fragName);
file = fopen(fragName, "rt");
if (file != NULL)
fscanf(file, "%d", &tmp);
}
int main()
{
readFrag("method/CoyoteAdapter.java.tk.method.514.5.533.5.bk");
return 0;
}
AVD is almost right -- you need to check your FILE* from fopen(3) to see if you actually opened the file. But his answer (and selbie's similar answer) both neglect the single most important piece of information: why the fopen(3) failed.
Try this:
void readFrag( char* fragName )
{
FILE *file;
int tmp;
file = fopen(fragName, "r");
if (!file) {
perror("Error reading fragment file in readFrag");
return;
}
fscanf(file, "%d", &tmp);
}
I also removed the t from the mode as I can't find any documentation anywhere that supports its use. I hope that this isn't the cause of the problem -- one would hope the libraries would be a bit more rigorous -- but because it is invalid input it certainly could be at fault. (Check your system's fopen(3) manpage and please correct me if I'm mistaken about your platform.)
Mostly likely the value of seq that you're passing in to your init function does not point at a pointer to valid memory (either seq itself is invalid, or *seq is)

read text file in xcode

i tried to read text file in xcode but this
"EXC_BAD_ACCESS message showed up when i tried to build my program
here is my code
and i put inputA.txt file in the same folder with project file
my friend told me that i should put txt file in debug folder is this why i cannot read txt
file in this code? please help me...
macbook user.
int main (int argc, const char * argv[]) {
FILE* fp;
char mychar;
char arr[50][2] = {0, };
int i = 0;
int j, k;
graphType* G_;
G_ = (graphType*)malloc(sizeof(graphType));
Create(G_);
fp = fopen("inputA.txt", "r");
//fp = fopen("inputB.txt", "r");
//fp = fopen("inputC.txt", "r");
while(1){
for(j = 0 ; j < 2 ; j++){
mychar = fgetc(fp);
if(mychar == EOF)
break;
else if(mychar == ' ')
continue;
arr[i][j] = mychar;
}
i++;
}
Per default your binary will be generated in ProjectDir/build/Mode, with Mode being Debug or Release, and will have that as its working directory. If you want to refer to a file in the project directory, you'd have to use ../../input.txt in that case.
The build locations are configured in the "Build Locations" section in a targets or projects build tab. The working directory can be manually changed in the settings for the executable ("General", "Set the working directory to:") if needed.
If you are having doubts then you can always find out what the working directory is:
#include <unistd.h>
int main() {
char buf[2048];
getcwd(buf, sizeof(buf));
printf("%s", buf);
}
Most likely inputA.txt is not in the same file as the binary. You should make sure the text file is copied to the output directory in your project (whether manually or by hand).
Also, fopen will return NULL if the file couldn't be opened, so you might want to add a check for that.
if (fp == NULL)
{
printf("Could not open file!");
return 1;
}
fopen is probably returning null because your text file isn't in the right place. Don't forget to check for null!

Resources