i was trying this problem from usaco. when i use txt file while using file the program is working fine. but when for the submission requirement i change the format to beads.in and beads.out the program crashes. what;s the problem?
here's my code:
#include <stdio.h>
#include<string.h>
main () {
FILE *fin = fopen ("beads.in", "r");
FILE *fout = fopen ("beads.out", "w");
int n;
char str[400];
char now,rev_now;
int pos,forward,reverse,sum,max=0,i,j,k;
fscanf(fin,"%d\n%s",&n,str);
n--;
for(pos=0;pos<=n;pos++){
now=str[pos];
if(pos==0)k=n;
else k=pos-1;
rev_now=str[k];
forward=2;
int flag1=0,flag2=0,reverse=2;
for(i=pos,j=k;;){
if(i==n)i=-1;
if((str[i+1]==now||str[i+1]=='w')&&flag1==0){
i++;
forward++;
}
else{
flag1=1;
}
if(j==0)j=n+1;
if((str[j-1]==rev_now||str[j-1]=='w')&&flag2==0){
j++;
reverse++;
}
else{
flag2=1;
}
if(flag1==1 && flag2==1)break;
}
sum=forward+reverse;
if(max<sum){max=sum;}
}
fprintf(fout,"%d\n",max);
return 0;
}
are you sure beads.in and beads.out are created already..
According to man page
r Open text file for reading. The stream is positioned at the
beginning of the file.
w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
May be beads.in is not created in prior to fopen. It's better if you check the status of the fopen, use perror.
You mention that it works with a text file. I'm guessing that beads.in is not a text file, but rather a binary file. If that is the case, then #KVD's suggestion above to use: fopen ("beads.in", "rb"); and fopen ("beads.out", "wb"); should work. The reason the program would crash with binary input data is because you are asking fscanf to copy data into your str buffer until it encounters a newline character. More than likely, the beads.in file has more than 400 characters which will cause a buffer overflow and start overwriting the program stack.
Related
Im supposed to write a program that opens an excel file, reads the numbers on the file, multiplies them by 9.8 and the shows the answer in another excel gile.
I wrote this, and I did not get any errors in the compiler, but when I run it, it does not open any files. How do I make it open the files?
#include <stdio.h>
int main() {
FILE *archivo;
FILE *archivoSalida;
int masa;
float peso;
archivo = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoEntrada.txt", "r");
archivoSalida = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoSalida.txt", "r");
if (archivo != NULL)
{
printf("The file was opened succesully");
while (fscanf(archivo,"%d", &masa)!= EOF)
{
peso=masa*9.81;
fprintf(archivoSalida, "%f\n", peso);
}
}
else
{
printf ("Error");
}
fclose(archivo);
fclose(archivoSalida);
return 0;
}
You'll want to fopen the output file ("archivoSalida") with mode "w" (for write) instead of "r" (for read). See e.g. http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html.
You do check if the input file could be opened (if (archivo != NULL)). Why don't you do the same for the output file?
Upon an error, you should output which error occured from errno, e.g. via perror(...). That should help in finding the actual problem.
Your file denominated by archivoSalida is opened in read mode ('r').
You should also check the return codes of read/writes functions to be sure everything happen as wanted.
The file names look Windows-ish. Is it possible that all of the forward slashes (/) that you have in both file names should really be back slashes (\)?
Why is the below program not printing the first character of the newly created text file ("E") as expected? It's a simple program and I tried to look at the issue from all aspects but couldn't find the reason. The text file is being created on my D drive with the content "EFGHI", but for some reason "E" is not being read even if I rewind and read using getc() and the output is -1.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x;
FILE *fp;
fp=fopen("F:\\demo.txt","w");
if(fp==NULL)
puts("Write error");
fputs("EFGHI",fp);
rewind(fp);
x=getc(fp);
printf("%d",x);
fclose(fp);
}
UPDATED:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x;
FILE *fp;
fp=fopen("F:\\demo.txt","w+");
if(fp==NULL)
{
puts("Write error");
exit(EXIT_SUCCESS);
}
fputs("EFGHI",fp);
rewind(fp);
while(!feof(fp))
{
x=getc(fp);
printf("%d\n",x);
}
fclose(fp);
}
File mode "w" opens the file for writing only.
Use "w+" to open a file for writing and reading.
(Please see man fopen for more file modes.)
Regarding getc() returning -1, verbatim from man getc:
[...] getc() [...] return[s] the character read as an unsigned char cast to an int or EOF on end of file or error.
EOF typically equals -1. To test this do a printf("EOF=%d\n", EOF);
fp=fopen("F:\\demo.txt","w");
Opens the file for writing, then you try to read from it. That's not going to work.
I'll also note that your program keeps trying to use fp even if it fails to be created since your if checking fp only prints an error, it doesn't stop the program.
I want to open a file, read its contents, and then append a line to the file. I thought I should use the "a+" flag for the task.
I have a function which opens a file and returns a pointer to this file.
FILE* open_weekly_disk_file(char* filename){
FILE* weekly_log;
weekly_log = fopen(filename, "a+");
//weekly_log = fopen(filename, "r");
if(! weekly_log){
printf("The attempt to open the weekly log failed!\n");
return NULL;
} else{
return weekly_log;
}
}
Then I have a function which calls the function above and uses scanf to read contents from the file:
void sample_function(char* filename){
FILE* log;
char token[100], current_read[100];
int limit;
log = opened_weekly_disk_file(filename);
// The problem happens here
for(limit=0; limit < TOKEN_NUMBER; limit++){
if(fscanf(log, "%s%s", &token, ¤t_read) == 2){
printf("%s %s\n", token, current_read);
}
}
...
}
This code works when I use:
weekly_log = fopen(filename, "r");
But does not work when I change the "r" flag to "a+". I get a Segmentation fault right before the for loop.
That is because the mode spec "a" opens a file for appending, with the file pointer at the end. If you try to read from here, there is no data since the file pointer is at EOF. You should open with "r+" for reading and writing. If you read the whole file before writing, then the file pointer will be correctly positioned to append when you write more data.
If this is not enough, please explore ftell() and fseek() functions.
from this SO QA
from the man page:
a+
Open for reading and appending (writing at end of file). The file is
created if it does not exist. The initial file position for reading is
at the beginning of the file, but output is always appended to the end
of the file.
Answer:
There is just one pointer which initially is at the start of the file
but when a write operation is attempted it is moved to the end of the
file. You can reposition it using fseek or rewind anywhere in the file
for reading, but writing operations will move it back to the end of
file.
So, the problem is not the fact that the file is opened in append mode, because it is not, as far as reading from it is concerned.
The problem lies in what your code does in those three dots
log = opened_weekly_disk_file(filename);
...
The code quite probably writes to the file, making the file cursor move to the end of it before the reading occurs.
i am trying to read integers from a file and fscanf doesn't work well with this code.
fp=fopen("record.dat","r");
if(fp==NULL)
{
printf("Another reading error");
}
else
{
printf("\nstarting to read\n");
i=0;
while(i<10)
{
if(fscanf(fp,"%d",&temp)>0)
printf("%d\n",temp);
i++;
}
fclose(fp);
}
the file contains 10 numbers which are delimited by a new line character. This code doesn't produce or print anything. What is the problem with the code and pls help me with it.
EDIT
the access mode as w+ or r isn't giving me a correct expected answer.
You are opening the file as a writable file instead of readable.
You must change "w+" to "r"
w+ The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
"w+" actually opens file for reading and writing. However, file is truncated to 0 length.
That might be the cause of printing blank lines.
Try "r+" (opens the file for reading and writing, without truncation) or "r".
This is my output function
void output(int n){
FILE *fp;
fp = fopen("sqrt.txt", "w");
for(int i = 1; i < n; ++i){
fprintf(fp, "%.2f\n", sqrt(i));
}
fclose(fp);
}
I'm required to make an input function (it reads the output function) that prompts the user to enter the name of the file to be opened. I need the contents of the file to be printed. If it is an invalid file name, the program should exit.
How to start this exercise?
To read a file in C, you use the fopen function almost just like what you had before, except passing it read rather than write. To read the file after it's been opened, you can use fread or fscanf. The file can be closed as usual with fclose.
If you want to read from the user rather than from a file, you can use fread with stdin instead of a file or (for the equivalent of fscanf) scanf.
fopen return a pointer that can be null: if it is, that mean your process was not able to open the file. So you have to check the return value of fopen to know if the file exist (I am not sure, but if the file exist and the return value is NULL, that means you probably have not the necessary right).
Hope it can help.