My code takes a string, writes it in a .dat file and then reads it from the .dat file and posts it in the console.
My problem is that the .dat from what I know should be coded, and I couldn't simply open it and see what's there. But when I open the d.at file with notepad, it behaves the same as a .txt file and I can see all it's written.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *f;
char s[100],g[100];
if((f=fopen("text.dat","wb"))==NULL)
{
exit(1);
}
printf("write text: "); gets(s);
int n=strlen(s);
fwrite(s,sizeof(s[0]),n,f);
fclose (f);
if((f=fopen("text.dat","rb"))==NULL)
{
exit(1);
}
fread(g,sizeof(g[0]),strlen(s),f);
puts(g);
return 0;
}
Nothing is wrong with your .dat file.
My problem is that the .dat from what I know should be coded
What does coded mean? Changing a file extension from .txt to .dat doesn't make any difference, in fact it's just renaming it. Microsoft Windows or any other OS may open specific file types with specific programs by default, but that doesn't mean that you can't use the program of your choice.
In this case, notepad will simply read the file contents, which are the characters you read from keyboard and written to it, without any "coding" (except ASCII encoding of course).
Related
At first I wanted to open a file and read its contents, in C, however, in doing so, I was unable to run the program without errors, I even tried to just open the file, and not read anything, I did exactly what I saw on other questions like this and got errors, here is the code.
#include <stdio.h>
void main(void){
FILE *file = NULL;
file = fopen('list.txt', 'r');
}
(Repeating BLUEPIXY's comment as an answer so search finds it)
Your mistake is that in 'list.txt', 'r' the ' does not mark a string in 'C' (unlike in python) you must use ".
The ' is used to specify `a single character variable.
First of all do you have a file called list.txt, and what if the program does not find list.txt. It can't read the file so you must check for exist file.
#include <stdio.h>
int main (void) {
FILE *file_exist = fopen("list.txt", "r");
if (file_exist) {
printf("File Founded");
//Insert what do you want to do with the file like fscanf? fgetc? Up to you
}
else {
printf("File Not Found");
//If there is no file, You can start ignore reading the file since will cause error dont know what to read
}
}
Here you can avoid error, while reading your file.
First of all, this is my fist stack overflow question, so forgive me if I format this wrong.
I am a beginner at C, and I am up to a point in my book on File i/o. The following code, which is supposed to print the lines to test.txt, doesn't create a new txt file or... do anything.
I am running Code Blocks 16.01 on Windows. Is this code designed for another OS?
#include <stdio.h>
#include <stdlib.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
Ok, so removing the slash makes it work. In the original code, it is 'fopen("/tmp/test.txt", "W+");'
Shouldn't this create the file in folder tmp?
Try removing the front-slash from the file name. You seem to be doing everything properly, the slash might be the problem. If not, let us know.
Edit: When I wrote my comment your fopen used "/test.txt" and not "/temp/test.txt", do you have the "temp" folder created in the directory the application is running from? If not, try creating it. Or remove it altogether and try creating the text file within the directory the application is running from.
Use double // in windows for navigate through directory.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
/*
file path in windows should be like this= C:\\users\\r.maurya\\Desktop\\Downloads\\file.txt
*/
fp = fopen("C:\\users\\r.maurya\\Desktop\\Downloads\\file.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
return 0;//Optional, On success of program
}
I am using fopen(3) in C to read file and process it. The file is present in current working directory where the binary exists, but I am unable to read the file (Linux environment / Cygwin environment).
Here is the sample code:
C code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *inFile;
static char fileName[255];
int process_file(FILE *inFile)
{
char ch;
inFile = fopen(fileName,"r");
if (inFile == NULL)
{
perror(fileName);
exit(1);
}
else
{
// Process file
}
fclose(inFile);
return 0;
}
int main(int argc, char *argv[])
{
printf("Enter filename to process \n");
scanf("%s", fileName);
process_file(inFile);
getchar();
return 0;
}
I have file permissions set to 777 in the current directory. The resulting binary as well as my source code reside in this directory where the input file exits. Why is the file not opened?
Update :
This question was written in few years back and this code could be improved a lot.
1. The process file should accept char * or char array instead of file pointer
2. unused variables can be removed
3. unused libraries or include files can be removed
4. Can make use of argv to accept filename with path from cmdline
5. return instead of exit in process_file and also proper return code instead of returning 0 from process_file.
I should have asked this question little more elaborate...
I had three functions to process the same file, like process_fil1e1(), process_file2() and process_file3() even though I called fclose() in all three functions. Somehow the file handle was not closed that properly or the file pointer pointed to EOF or some undefined behavior. It was not working fine.
When I used a single process file and rewind() together, it worked fine...
Be sure to input file name with its extension. This may cause problems with reading the file.
If you know the extension of the file you can input only the name and after that make the program add the extension. After scanf("%s", fileName); add strcat(fileName, ".txt"); if you want to enter only the name without extension and the file you read has extension .txt.
Your inFile and fileName variables are extern so you don't need to have arguments for the function process_file();, any function can access those variables.
You can change function int process_file(); to void process_file(); and delete return 0, you don't need that.
You have declared the inFile and fileName as global. You should change your function prototype from
int process_file(FILE *inFile)
to
int process_file()
This would at least make your program more clear. Now regarding your problem: It would almost certain be that you are doing something wrong in the input file (like not putting in the file extension) in your input. Remember, you need to pass the complete file name (including the extension which on some systems like Windows (by default) would be hidden). Otherwise, the logic looks correct to me, and it should work fine.
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.
I am working on TTCN-3 (Testing and Test Control Notation) scripting language. I wanted to prepare on guideline checker for this code files.
For that I want to read lines of TTCN-3 script file( some thing like file.ttcn ) one by one into a buffer. But for me fopen / sopen / open / fgetc / fscanf are not able to work properly and are not reading the file correctly. It is giving NULL. Is there any way I can read characters of it into a buffer. I think C cannot read files with more than three extension characters (like .ttcn). Forgive me if my assumption is wrong.
My Environment is Turbo C on windows.
Edit:
Yes I checked those errors also but they are giving unknown error for read()
and no such file or directory exists.
My code is as follows
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
int handle;
int status;
int i=0;
char ch;
FILE *fp;
char *buffer;
char *buf;
clrscr();
handle = sopen("c:\\tc\\bin\\hi.ttcn", O_BINARY, SH_DENYNONE, S_IREAD);
/here even I used O_TEXT and others/
if (!handle)
{
printf("sopen failed\n");
// exit(1);
}
printf("\nObtained string %s #",buf);
close(handle);
fp=fopen("c:\\tc\\bin\\hi.ttcn","r"); \\sorry for the old version of one slash
if(fp==NULL) \\I was doing it with argv[1] for opening
{ \\user given file name
printf("\nCannot open file");
}
ch=fgetc(fp);
i=0;
while(i<10)
{
printf("\ncharacter is %c %d",ch,ch);
i++; //Here I wanted to take characters into
ch=fgetc(fp); //buffer
}
getch();
return 0;
}
The most likely culprit is your Turbo C, an ancient compiler. It's techincally a DOS compiler, not Windows. That would limit it's RunTme Library to 8.3 filenames. Upgrade to something newer - Turbo C++ seems like a logical successor, but Microsoft's VC++ Express would work as well.
Your assumption is wrong about extensions. If fopen is returning NULL, you should output the result of strerror(errno) or use the perror() function to see why it failed.
Edit: The problem is probably because you have "c:\tc\bin\hi.ttcn". in C, "\t" is interpreted as tab, for example.
You could do
"c:\\tc\\bin\\hi.ttcn"
But this is extremely ugly, and your system should accept:
"c:/tc/bin/hi.ttcn"
MS-DOS does not know about long file names, thos including files with extensions longer than 3 characters. Therefore, the CRT provided by Turbo C most probably does not look for the name you are providing, but a truncated one - or something else.
Windows conveniently provides a short (i.e. matching the 8.3 format, most of the time ending in ~1 unless you play with files having the same 8-character prefix) file name for those; one way to discover it is to open a console window and to run "dir /x" in the folder your file is stored.
Find the short name associated to your file and patch it into your C source file.
Edit: Darn, I'll read the comments next time. All credits to j_random_hacker.
Now that you've posted the code, another problem comes to light.
The following line:
fp=fopen("c:\tc\bin\hi.ttcn","r");
Should instead read:
fp=fopen("c:\\tc\\bin\\hi.ttcn","r");
In C strings, the backslash (\) is an escape character that is used to encode special characters (e.g. \n represents a newline character, \t a tab character). To actually use a literal backslash, you need to double it. As it stands, the compiler is actually trying to open a file named "C:<tab>c<backspace>in\hi.ttcn" -- needless to say, no such file exists!