How to read a file in C from a subdirectory - c

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)

Related

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;

stream != nullptr visual studio, simply printing values from txt file (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");
}

I want to copy my in file on to my out file.

In this code I opened my files in my open_file function. Then the process_file function needs to copy the text from my in file and Copy it to an out file. Right now it produces a new file but it is blank. It does not give me any error messages. I do not know what is wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_LEN 100
FILE* open_file(char prompt[], char mode[]);
FILE* process_file(FILE* in, FILE* out);
int main(int argc, const char * argv[]) {
FILE* in = NULL;
FILE* out = NULL;
printf("MAD-LIBS Text Processor\n");
printf("The Program will open a mad-libs file, ask you to fill various words, and produce a funny story.\n");
open_file("Enter mad-lib file name:\n", "r");
open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
fclose(in);
fclose(out);
return 0;
}
/* open_file = prompts user for file name & and attempts to open it, if it fails it prompts the user again. */
FILE* open_file(char prompt [], char mode[]) {
char filename[255];
FILE* in;
do {
printf("%s", prompt);
scanf("%s", filename);
in = fopen(filename, mode);
if (in == NULL) {
printf("Unable to open file: %s. Try Again!\n", filename);
}
} while(in == NULL);
return in;
}
/* process_file = processes entire input file and writes it to output file */
FILE* process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
char NewContent[MAX_LEN];
//gets whats in file in
while(fgets(content, content[MAX_LEN], in) != NULL) {
fputs (content, stdout);
strcat(NewContent, content);
}
// copies it
while (fgets(content, content[MAX_LEN], in) != NULL) {
fprintf(out, "%s", content);
}
printf("Successfully copied file\n");
return in;
}
You never assign the FILE* from open_file function to your variable, so it never gets processed.
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
You are not storing the FILE pointers that open_file is returning, so in
and out remain uninitialized.
You have to do:
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
Also your process_file is wrong. NewContent is not initialized, when you do
strcat(NewContent, content);
this yields undefined behaviour. Declare NewContent like this:
char NewContent[MAX_LEN] = { 0 };
so that it is properly \0-terminated.
Also depending on the size of the file you are copying, MAX_LEN might not be
long enough to hold the whole file. In that case you would overflow the buffer.
It would be better not to use NewContent in the first place and write to out
in the same reading loop:
FILE* process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
//gets whats in file in
while(fgets(content, MAX_LEN, in) != NULL) { //<- your fgets was wrong
fputs (content, stdout);
fprintf(out, "%s", content); // or fputs(content, out);
}
printf("Successfully copied file\n");
return in;
}
And you were calling fgets incorrectly (look at my corrected code)
Also bear in mind, that you did have 2 loop doing while(fgets(...) != NULL.
Well, the first loop ends, that's because fgets returns NULL, most likely
because the whole file was read or there was an I/O error. In either case
subsequent calls of fgets will return NULL as well, so your second loop
would not even be executed at all.

How to call a File pointer in a function

I need to scan a file for letters to form a scrambled word. Everything looks okay but the debugger doesnt execute the command. Any advice would be greatly appreciated.
Code:
void playGame(char array1[SIZE], FILE*aPtr)
{
aPtr = fopen("words.txt", "r");
int i;
for (i = 0; i < SIZE; i++){
fscanf(aPtr, " %c", array1[i]);
printf("%c", array1[i]);
}
}
Heres how I call the function in main
playGame(&scramble[SIZE], inPtr);
the array scramble[] is declared as is the FILE*inPtr, Also, SIZE is defined as 10.
In your calling code, you have:
FILE *fp = 0;
char game[SIZE];
Given that you're opening the file in the function, but not closing it, you need to change the file in the function, so the call could be:
playGame(game, &fp);
if (fp != 0)
fclose(fp);
But the function should be changed to:
void playGame(char array1[SIZE], FILE **aPtr)
{
FILE *fp = fopen("words.txt", "r");
if (fp != 0)
{
*aPtr = fp;
...other code...
}
}
Alternatively, the file should be opened and closed in the calling code and the file pointer simply passed to playGame():
FILE *fp = fopen("words.txt", "r");
if (fp != 0)
{
playGame(game, fp);
fclose(fp);
}
With this interface, there is no fopen() (or fclose()) call in playGame(), which keeps its current interface (void playGame(char game[SIZE], FILE *fp)). This makes more sense. Very often it is correct for the function that opens a file to be responsible for closing it too. There are exceptions, but not all that many of them.

Reading a text file line by line and saving to an array (C Language)

Here's my issue:
I'm currently working on a project for university. We're suppose to do a program that receives .pbm and .pgm files as input, and then we're suppose to handle them in some ways. But for now the main thing is to successfully receive them.
Each .pbm and .pgm file's first line is a "magic number". A set of characters like P1, P2 (...) P6.
Our goal is to receive a .pbm file as input, save the first line, dynamically allocate a string so it is just as big as its content (P6\n, for example), so we can then detect the magic number. The same applies to every other line. We basically just want a way to save each line into an array, making them just as big as their content.
Me and my project partner are both beginners: file handling, pointers, dynamic memory and headers are still pretty hard to us. Thank you in advance.
---EDIT--- (Forgot the code, as an user pointed out)
int main(int argc, char const *argv[])
{
readFile(argv[1], "EI_2012-13_ascii.pbm");
return 0;
}
void readFile (const char* input_file, char* filename){
char *line_buffer, *line;
FILE *file_stream = NULL;
if(!check_extension(filename, ".pbm") &&
!check_extension(filename, ".pgm") && !check_extension(filename, ".ppm"))
ERROR(ERR_EXT, "Invalid file extension!\n");
file_stream = fopen(input_file, "r");
if (file_stream == NULL)
ERROR(ERR_EXT, "Couldn't open the file for reading");
line_buffer = malloc(sizeof(2));
fscanf(file_stream, "%s", line_buffer);
//line = strchr(line_buffer, '\n');
printf("%s\n", line_buffer);
printf("%d\n", sizeof(line_buffer));
fclose(file_stream);
}
With this code we were attempting to output a string and its size underneath it. Strangely we keep getting the same output: 4. We needed that the malloc received a proper argument, the size of the line until the '\n'.
You can detect the magic number reading the file line by line using Linux function getline() as shown below,
void readFile (const char* input_file, char* filename){
char *line;
FILE *file_stream = NULL;
ssize_t read; size_t len = 0;
file_stream = fopen(input_file, "r");
if (file_stream == NULL)
ERROR(ERR_EXT, "Couldn't open the file for reading");
while((read = getline(&line, &len, file_stream)) != 1){
printf("%s", line);
printf("length of line: %zu\n", read);
}
if (line)
free(line);
fclose(file_stream);
}

Resources