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.
Related
i'm testing the fgetc() function but it doesn't work properly (i have used this function befor so i know how it works)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = NULL;
int n;
file = fopen("test.txt", "w+");
if(file != NULL)
{
fputs("ab", file);
printf("%c", fgetc(file));
}
else
{
printf("error");
}
return 0;
}
the output should be "a" but it's somthing else
The file is opened for both writing and reading but you need to fseek to the correct place in the file (here, the beginning). In particular, when switching between writing and reading you need to fseek or fflush.
When the "r+", "w+", or "a+" access type is specified, both reading
and writing are enabled (the file is said to be open for "update").
However, when you switch from reading to writing, the input operation
must encounter an EOF marker. If there is no EOF, you must use an
intervening call to a file positioning function. The file positioning
functions are fsetpos, fseek, and rewind. When you switch from writing
to reading, you must use an intervening call to either fflush or to a
file positioning function.
In any case, after writing to the file, the file pointer is in the wrong place to read what was just written.
So the code becomes
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file = NULL;
file = fopen("test.txt", "w+");
if(file != NULL) {
fputs("ab", file);
fseek(file, 0, SEEK_SET);
printf("%c", fgetc(file));
fclose(file);
}
else {
printf("error");
}
return 0;
}
And if you want to continue writing to the file, you must fseek to its end.
Your error is that you are trying to read a file that has been opened for writting. You should write inside it, then close the file and reopen it for reading. This code will show what I am telling:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fileRead, *fileWrite = NULL;
int n;
fileWrite = fopen("test.txt", "w+");
if(fileWrite != NULL)
{
fputs("ab", fileWrite);
fclose(fileWrite);
}
else
{
printf("error");
}
// Open again the file for read
fileRead = fopen("test.txt", "r");
printf("%c", fgetc(fileRead));
fclose(fileWrite);
// End function
return 0;
}
I have an issue with writing strings into a txt file. My lines get overwritten every time. I use
gcc -Wall -o filename filename.c to compile and ./filename 10 Berlin cat resultat.txt to execute.
The txt file always has just one line (the last one) how can I save all the records.
I have a CSV file with city names and a number of residents, I need to filter for the City name and a minimum of residents.
What I tried so far:
.....
void write_file(char *result[], int len) {
FILE *fp = fopen("resultat.txt", "w");
if (fp == NULL){
perror("resultat.txt");
exit(1);
}
for (int i=0; i<len; i++) {
fprintf(fp, "%s\n", result[i]);
}
fclose(fp);
}
int main(int argc,char **argv) {
int anzahl = atoi(argv[1]);
char *string_array[100];
char *erste_zeile;
erste_zeile = (char *) malloc(1000 * sizeof(char));
char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
int bewohner[MAX_LAENGE_ARR];
int len = read_file("staedte.csv", staedte, laender, bewohner);
for (int i = 0; i < len; ++i){
if (strcmp(argv[2],laender[i])==0 && anzahl < bewohner[i]){
snprintf(erste_zeile, 100,"Die Stadt %s hat %d Einwohner\n",staedte[i],bewohner[i]);
string_array[0] = erste_zeile;
// counter++;
write_file(string_array,1);
}
}
free(erste_zeile);
return 0;
}
Using the write_file() function outside of the for loop gives me null values. If anybody has an idea how to optimize the code please leave a comment or answer.
Each time you use FILE *fp = fopen("resultat.txt", "w"); what this does is delete the existing file and create a blank file for writing. What you're looking for is FILE *fp = fopen("resultat.txt", "a"); //a not w!. This will open the existing file and append content. If a file does not exist, one will be created. See this reference.
"w" -
Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
"a" -
Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
Also heed #Serge's advice about not opening the file for each record. Just open it once in the main and use the file handle to write to it. To make your current code work, you can do this:
void write_file(char *result[], int len) {
FILE *fp = fopen("resultat.txt", "a");//open for append
if (fp == NULL){
perror("resultat.txt");
exit(1);
}
for (int i=0; i < len; i++) {
fprintf(fp, "%s\n", result[i]);
}
fclose(fp);
}
I'm writing a wrapper to help me in my future projects (I finished C book), and want to copy a file without using fgetc. Here's my code, it doesn't work:
int CopyFile(char* filename, char* dest)
{
FILE* fp, *fout;
fp = fopen(filename,"rb");
//fout = fopen(dest, "wb");
if(fp == NULL)
{
return -1;
}
/*while((c = fgetc(fp)) != EOF)
{
fputc(c,fout);
}*/
long size = GetFileSize(fp);
printf("%lu", size);
char* file = malloc(size);
fread(file, size, 1, fp);
//fclose(fp);
fout = fopen(dest, "wb");
fwrite(file, size, 1, fout);
fclose(fp);
fclose(fout);
return 0;
}
I even open the files with a hexeditor and they aren't similar. What am I doing wrong?
The problem is in the GetFileSize function, where you move the file-pointer to the end, but you never rewind to the beginning again.
That means your fread function call will not actually read anything, as the pointer already is at the end of the file. So what's written is the contents of the allocated memory, which is indeterminate (and will be seemingly random).
If you checked what fread returned, you would have seen this immediately.
Let this be a lesson on always checking the return values of functions which can fail in one way or the other.
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)
I have searched the site and I haven't found an answer to my problem.
My program outputs an image, and I want to save to a different file, each image produced after an cycle iteration.
My code to save files is this
FILE *fobjecto;
if ((fobjecto = fopen ("OSEM.ima", "wb")) != NULL)
{
printf("Writing reconstructed image file");
fwrite (objecto, sizeof(float), (detectorXDim)*detectorYDim*(NSlices-1), fobjecto);
fclose (fobjecto);
}
else
printf("Reconstructed image file could not be saved");
I want to add one integer variable to the output file's name, I have tried playing with "+" and "," but I could not solve it.
Thanks in advance
You will need some formatted output operation like sprintf (or even better its safe twin snprintf):
char buf[512]; // something big enough to hold the filename
unsigned int counter;
FILE * fobjecto;
for (counter = 0; ; ++counter)
{
snprintf(buf, 512, "OSEM_%04u.ima", counter);
if ((fobjecto = fopen(buf, "wb")) != NULL) { /* ... etc. ... */ }
// Filenames are OSEM_0000.ima, OSEM_0001.ima, etc.
}
char file_name[256];
sprintf(file_name, "OSEM%4.4d.ima", iteration_count);
if (NULL!=(fobjecto=fopen(file_name, "wb")))
// ...
construct the file name before you open it:
char filename[256];
//...
sprintf(filename, "OSEM%08X.ima", someIntegerToAddAsHex);
if ((fobjecto = fopen (filename, "wb")) != NULL)
//...